【C】C++标准模板库(STL)介绍--set

时间:2021-12-10 10:16:32

2.set---自动有序且去重

set只能通过迭代器访问

.insert(x)

.find(value)---返回迭代器printf(%d,*it);//printf(%d,*(set.find(x)));

.erase(it)

.erase(value)

.erase(first,last)

.size()

.clear()


1063. Set Similarity (25)

时间限制
300 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
33 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<stdio.h>#include<set>using namespace std;set<int> buf[51];//最多有50组double compare(int x,int y){	set<int>::iterator it;	int totalnum=buf[y].size();//因为下文是遍历buf[x],所以这里的起始总和应该是y的数量	int sharenum=0;	for(it=buf[x].begin();it!=buf[x].end();it++){		if(buf[y].find(*it)!=buf[y].end()) sharenum++;		else totalnum++;	}	//printf("%d %d\n",sharenum,totalnum);	return (double)sharenum/(double)totalnum*100;}int main(){	int n,i,j;	double ct[2001];	scanf("%d",&n);	for(i=1;i<=n;i++){		int m,a;		scanf("%d",&m);		for(j=0;j<m;j++){			scanf("%d",&a);			buf[i].insert(a);		}	}	int k;	scanf("%d",&k);	for(i=0;i<k;i++){		int a1,a2;		scanf("%d %d",&a1,&a2);		/*int len1=buf[a1].size();		int len2=buf[a2].size();		set<int> buff;		for(j=0;j<len1;j++){			set<int>::iterator it;			for(it=buf[a1].begin();it!=buf[a1].end();it++){				buff.insert(*it);			}		}		for(j=0;j<len2;j++){			set<int>::iterator it;			for(it=buf[a2].begin();it!=buf[a2].end();it++){				buff.insert(*it);			}		}		int len=buff.size();		int nc=len1+len2-len;		int nt=len;		ct[i]=(double)nc/(double)nt*100;*/		//以上插入给一个新的set,超时		ct[i]=compare(a1,a2);	}	for(i=0;i<k;i++){		printf("%.1f%%\n",ct[i]);	}	return 0;}