1063 Set Similarity (25 分)求集合交集並集比值
題目
Given two sets of integers, the similarity of the sets is defined to be , where is the number of distinct common numbers shared by the two sets, and 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
which is the total number of sets. Then N lines follow, each gives a set with a positive
and followed by M integers in the range
. After the input of sets, a positive integer
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%
解題思路
題目大意: 給定N個集合,求任意連個集合的交集元素比上並集元素個數的比值。
解題思路: 這道題的思路並不難,關鍵在於怎麼實現集合的交集和並集,以及如何實現集合。直接使用stl中的set能夠快速的解決這一問題。我們直接在此基礎上統計不同的元素個數,即得到集合交集的元素個數,然後,我們直接用兩個集合元素個數之和減去交集個數,得到並集個數,最後直接比值即可。
/*
** @Brief:No.1063 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2018-12-28
** @Solution: https://blog.csdn.net/CV_Jason/article/details/85329420
*/
#include<iostream>
#include<set>
#include<map>
using namespace std;
int main(){
int N,M,K,temp;
while(scanf("%d",&N)!=EOF){
set<int> st[N];
for(int i=0;i<N;i++){
scanf("%d",&M);
for(int j=0;j<M;j++){
scanf("%d",&temp);
st[i].insert(temp);
}
}
int a,b;
scanf("%d",&K);
for(int i=0;i<K;i++){
scanf("%d%d",&a,&b);
int nc=0,nt=0;
for(auto it = st[a-1].begin();it!=st[a-1].end();it++){
if(st[b-1].find(*it)!=st[b-1].end()){
nc++;
}
}
nt = st[b-1].size()+st[a-1].size()-nc;
printf("%.1f%%\n",nc*100.0/nt);
}
}
return 0;
}
總結
最開始用set+map的組合進行集合運算,使用map是為了方便統計不同元素的個數,用元素出現次數作為value,結果最後一個點超時了,由於我對set和map的時空效能不是很熟悉,看了別人的答案,有set+find演算法過的,看來map還是很耗時的。