L2-005. Set similarity
Given two sets of integers, their similarity is defined as Nc/Nt*100%. Where Nc is the number of unequal integers in both sets, Nt is the number of unequal integers in both sets. Your task is to calculate the similarity of any given set.
Input format:
Enter the first line to give a positive integer N (< 50), which is the number of sets. Then N lines, each corresponding to a set. Each set first gives a positive integer m (< 104), which is the number of elements in the set, and then M integers in the [0, 109] interval.
The next line gives a positive integer k (< 2000), and then the K line corresponds to the number of a pair of sets that need to calculate the similarity (set number from 1 to N). Numbers are separated by spaces.
Output format:
For each pair of sets that need to be calculated, their similarity is output in a row, which is a percentage number of two decimal places.
Input example:3 3 99 87 101 4 87 101 5 87 7 99 101 18 5 135 18 99 2 1 2 1 3Output example:
50.00% 33.33%
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <map> using namespace std; #define N 100 map<int,bool>mp[N]; int num[N][10011], ss[N]; void judge(int m, int n) { double fenm=ss[m]+ss[n], fenz=0; int i=0, j=0; while(i<ss[m]&&j<ss[n]) { if(num[m][i]==num[n][j]) { i++,j++,fenz+=1; } else if(num[m][i]>num[n][j]) { j++; } else { i++; } } printf("%.2f%%\n",(fenz/(fenm-fenz))*100); } int main() { int n; cin>>n; for(int i=1; i<=n; i++) { mp[i].clear(); int cnt=0; int m, x; cin>>m; for(int j=0; j<m; j++) { cin>>x; if(!mp[i][x]) { mp[i][x]=true; num[i][cnt++]=x; } } ss[i]=cnt; sort(num[i],num[i]+cnt); } int k; cin>>k; while(k--) { int a, b; cin>>a>>b; judge(a,b); } return 0; }
Using set
#include<iostream> #include<stdio.h> #include<set> using namespace std; int main() { int n,m; scanf("%d",&n); set<int>num[55]; int temp; for(int i = 1; i <= n; i++) { scanf("%d",&m); for(int j = 1; j <= m; j++) scanf("%d",&temp),num[i].insert(temp); } int k,a,b; set<int>s; set<int>::iterator rit; scanf("%d",&k); for(int i = 1; i <= k; i++) { scanf("%d%d",&a,&b); int con=0; for(rit=num[a].begin();rit!=num[a].end();rit++) if(num[b].count(*rit)) con++; printf("%.2lf%%\n",100.0*con/(num[a].size()+num[b].size()-con)); } return 0; }