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 (≤10^4)
and followed by M integers in the range [0,10^9]. 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 3
Sample Output:
50.0%
33.3%
要注意除开vector与string容器都不支持*(it + i)的访问方式,也就是不能像数组一样对元素进行访问
#include<stdio.h>
#include<set>
using namespace std;
const int N = 55;
set<int> st[N]; //与vector类似,这样相当于定义一个二维数组a[m][n],其中m定长,n不定长
void find_sanme(int a, int b) {
int sameNum = 0; //记录并集中数据的总个数以及两个几个相同元素个数
int totalNum = st[b].size();
for(set<int>::iterator it = st[a].begin(); it != st[a].end(); ++it) {
//在st[a]中取出*it,接着在st[b]寻找该元素,找得到则相同,如果知道最后一个
//都找不到,则说明两个集合不再等长,则更新并集总元素个数
if(st[b].find(*it) != st[b].end()) {
sameNum++;
} else {
totalNum++;
}
}
/*for(int i = 0; i < st[a].size() || i < st[b].size(); ++i) {
//set中无法通过st[i]直接访问元素
if(st[a][i] == st[b][i]) {
sameNum++;
}
totalNum++:
}*/
printf("%.1f%%\n", sameNum * 100.0 / totalNum);
}
int main() {
int n;
scanf("%d", &n);
for(int i = 1; i <= n; ++i) { //从1开始
int k; //每组数据的数据个数
scanf("%d", &k);
for(int j = 0; j < k; ++j) {
int temp;
scanf("%d", &temp);
st[i].insert(temp); //将数据插入st[i]中
}
}
int h;
scanf("%d", &h); //输入查询次数
for(int i = 0; i < h; ++i) {
int a, b; //输入查询编号
scanf("%d %d", &a, &b);
find_sanme(a, b);
}
return 0;
} ```