PAT甲级1063 Set Similarity (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​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%

二、解题思路

把题目的意思搞明白之后其实就不难了,两个集合的相似性就是两个集合中相同的元素数目除以总的元素数目(注意这个总的数目也是要去掉重复元素的)。我们可以直接把题目输入的数据存入一个set中,set里面的元素是会自动去重的,用st.find()函数找到相同元素的个数,然后用st.size()函数来计算总元素数目大小,最后进行简单计算输出即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
using namespace std;
int main()
{
    
    
  int N, num, tmp, a, b;
  scanf("%d", &N);
  vector<set<int> > st(N+1);
  for(int i=1; i<=N; i++)
  {
    
    
    scanf("%d", &num);
    for(int j=0; j<num; j++)
    {
    
    
      scanf("%d", &tmp);
      st[i].insert(tmp);
    }
  }
  scanf("%d", &num);
  for(int i=0; i<num; i++)
  {
    
    
    int cnt = 0;
    double ans = 0.0;
    scanf("%d%d", &a, &b);
    int sze1 = st[a].size(), sze2 = st[b].size();
    for(set<int>::iterator it=st[a].begin(); it!=st[a].end(); it++)
      if(st[b].find(*it) != st[b].end())	cnt++;
    ans = (cnt*1.0)/((sze1+sze2-cnt)*1.0);
    ans *= 100;
    printf("%.1f\%\n", ans);
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108659314