1063. Set Similarity (25)
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:3 3 99 87 101 4 87 101 5 87 7 99 101 18 5 135 18 99 2 1 2 1 3Sample Output:
50.0% 33.3%
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int num[51][10001]; int sm[51], tmp[20010]; void outPut(int a, int b) { int nc = 0, nt = 0, nn, i; for(i = 0; i < sm[a]; i++) tmp[i] = num[a][i]; for(; i < sm[a] + sm[b]; i++) tmp[i] = num[b][i-sm[a]]; sort(tmp, tmp + sm[a] + sm[b]); for(i = 0; i < sm[a] + sm[b]; i++) { if(i == 0) { nt++; nn = 1; } else { if(tmp[i] != tmp[i-1]) { nt++; nn = 1; } else if(tmp[i] == tmp[i-1]) { nn++; if(nn == 2) nc++; } } } printf("%.1lf", (1.0 * nc) / (1.0 * nt) * 100); printf("%%\n"); } int main() { int i, j, a, b, cc, tt; int n, m; while(scanf("%d", &n) != EOF) { for(i = 0; i < n; i++) { scanf("%d", &sm[i]); for(j = 0, a = 0; j < sm[i]; j++) { scanf("%d", &tt); for(cc = 0; cc < a; cc++) if(num[i][cc] == tt) //将each of sets 中的same data delete break; if(cc == a) num[i][a++] = tt; } sm[i] = a; } scanf("%d", &m); for(i = 0; i < m; i++) { scanf("%d%d", &a, &b); outPut(a-1, b-1); } } return 0; }
此博客介绍了一种计算两个集合相似度的方法,通过比较共享元素的数量和总元素数量来得出百分比形式的结果。
205

被折叠的 条评论
为什么被折叠?



