PAT1063 Set Similarity

题目

Given two sets of integers, the similarity of the sets is defined to be N~c~/N~t~*100%, where N~c~ is the number of distinct common numbers shared by the two sets, and N~t~ 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 (<=10^4^) and followed by M integers in the range [0, 10^9^]. 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%

超时代码:

#include <iostream>
#include <cstdio>
#include <set>
#include <algorithm> 
#include <vector> 
using namespace std;
vector<int> ST[51]; 
set<int> ET,FT,GT;
int main()
{
	// freopen("8.txt","r",stdin);
	int N, M, K, N1, N2;
	int p, q;
	scanf("%d",&N);
	for(int i=1; i<=N; i++){
		scanf("%d",&M);
		for(int j =0; j < M; j++){
			scanf("%d",&p);
			ST[i].push_back(p);
		}
	}
	scanf("%d",&K);
	for(int i = 0; i < K; i++){
		scanf("%d%d",&N1,&N2);
		int a = 0, b = 0;
		while(a<ST[N1].size()&&b<ST[N2].size()){
			ET.insert(ST[N1][a]);
			FT.insert(ST[N2][b]);
			GT.insert(ST[N1][a]);
			GT.insert(ST[N2][b]);
			a++;
			b++;
		}
		while(a < ST[N1].size()){
			ET.insert(ST[N1][a]);
			GT.insert(ST[N1][a]);
			a++;
		}
		while(b < ST[N2].size()){	
			FT.insert(ST[N2][b]);
			GT.insert(ST[N2][b]);
			b++;
		}
		double c = 100.0*(ET.size()+FT.size()-GT.size())/GT.size();
		printf("%.1lf",c);
		printf("%\n");
		ET.clear();
		FT.clear();
		GT.clear();
	}
	

} 

AC代码:

#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
set<int> ST[51];

void mycompare(int x, int y){
	int totalNum = ST[y].size(), sameNum = 0;
	for(set<int>::iterator it = ST[x].begin(); it != ST[x].end(); it++){
		if(ST[y].find(*it) != ST[y].end())  sameNum++;
		else          totalNum++;
	}
	double c = 100.0*sameNum/totalNum;
	printf("%.1lf",c);
	printf("%\n");
}
int main()
{
	 freopen("8.txt","r",stdin);
	int N, M, K, N1, N2;
	int p;
	scanf("%d",&N);
	for(int i=1; i<=N; i++){
		scanf("%d",&M);
		for(int j =0; j < M; j++){
			scanf("%d",&p);
			ST[i].insert(p);
		}
	}
	scanf("%d",&K);
	for(int i = 0; i < K; i++){
		scanf("%d%d",&N1,&N2);
		mycompare(N1,N2);
	}
	return 0;

	
	
	
}

导致超时的原因:没有利用好set容器,导致繁琐多余的操作。

猜你喜欢

转载自blog.csdn.net/weixin_41168353/article/details/81177302