【PAT】A1063. Set Similarity (25)

Description:
Given two sets of integers, the similarity of the sets is defined to be Nc/Nt*100%, where Nc is the number of distinct common numbers shared by the two sets, and Nt is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

Input Specification:

Each input file contains one test case. Each case first gives a positive integer N (<=50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (<=104) and followed by M integers in the range [0, 109]. After the input of sets, a positive integer K (<=2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.

Output Specification:

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

Sample Input:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3


Sample Output:
50.0%
33.3%

一个超时的程序:

//NKW 甲级真题1021
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <set>
using namespace std;
set<int> vs[60], st;
int main(){
	int n, m, k, num;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++){
		scanf("%d", &m);
		while (m--){
			scanf("%d", &num);
			vs[i].insert(num);
		}
	}
	scanf("%d", &k);
	for (int i = 0; i < k; i++){
		scanf("%d %d", &n, &m);
		double len1 = vs[n].size(), len2 = vs[m].size(), len3;
		st.clear();
		for (set<int>::iterator it = vs[n].begin(); it != vs[n].end(); it++)
			st.insert(*it);
		for (set<int>::iterator it = vs[m].begin(); it != vs[m].end(); it++)
			st.insert(*it);
		len3 = st.size();
		printf("%.1f%%\n", (len2 - len3 + len1) / len3 * 100);
	}
	system("pause");
	return 0;
}

AC:

//NKW 甲级真题1021
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <set>
using namespace std;
set<int> vs[60];
int main(){
	int n, m, k, num;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++){
		scanf("%d", &m);
		while (m--){
			scanf("%d", &num);
			vs[i].insert(num);
		}
	}
	scanf("%d", &k);
	for (int i = 0; i < k; i++){
		scanf("%d %d", &n, &m);
		double nc = 0, nt = vs[m].size();
		for (set<int>::iterator it = vs[n].begin(); it != vs[n].end(); it++){
			if (vs[m].find(*it) != vs[m].end())		nc++;
			else	nt++;
		}
		printf("%.1f%%\n", nc / nt * 100);
	}
	system("pause");
	return 0;
}

程序分析:

虽然find()和insert()的时间复杂度都是O(logn),第一个是O(klogn+klogm),第二个是O(klogn)。

set<int> st;

st.find(value),如果找到元素返回value的迭代器,如果没找到返回st.end()。

猜你喜欢

转载自blog.csdn.net/ztmajor/article/details/81172657