A1063 Set Similarity (25point(s))
题意
输入n个set,k次查询,输入两个set的id,输出他们之间的相似度,相似度计算公式为 共同元素个数/它们的并集的size
思路
maps[v] 储存v值在的集合的id。
还要一种做法是联合两个set。
总结
判断key是否在map中的时候一定要用count()方法,不然会插入大量无用节点,使得查找性能变差。
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"bits/stdc++.h"
using namespace std;
#define ll long long
unordered_map<ll,unordered_map<int,int>> maps;
int main(){
freopen("input.txt","r",stdin);
int n; cin >> n;
vector<unordered_set<ll> > sets(n);
for(int i=0;i<n;i++){
int m; scanf("%d",&m);
for(int j=0;j<m;j++){
ll t; scanf("%lld",&t);
sets[i].insert(t);
maps[t][i] = 1;
}
}
int k; cin >> k;
for(int i=0;i<k;i++){
int t1,t2; scanf("%d%d",&t1,&t2);
t1 --; t2--;
int cnt = 0; // share
if(sets[t1].size() < sets[t2].size()){
for(ll v:sets[t2]) if(maps[v].count(t1)) cnt++;
}else
for(ll v:sets[t1]) if(maps[v].count(t2)) cnt++;
int total = sets[t1].size() + sets[t2].size() - cnt;
printf("%.1f%\n",cnt*1.0 / total * 100);
}
}