【PAT】A1063 Set Similarity【Set的使用】

Given two sets of integers, the similarity of the sets is defined to be N​c​​/N​t​​×100%, where N​c​​ is the number of distinct common numbers shared by the two sets, and N​t​​ 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%

给定两组整数,这些集合的相似性定义为N​C​​/N​T​​×100%,其中N​C​​ 是两个集合共享的不同公共数的数目,N​T​​ 是两组中不同数字的总数。您的工作是计算任何给定集合对的相似性。

输入规格:

每个输入文件包含一个测试用例。每种情况首先给出一个正整数N(≤50)这是总套数。然后N行跟随,每行给出一个正M的集合(≤10​4.​​) 后跟[0,10]范围内的M个整数​^9​​]. 输入集合后,一个正整数K(≤2000),然后是K行查询。每个查询提供一对集合编号(集合编号范围为1到N)。一行中的所有数字都用空格分隔。

输出规格:

对于每个查询,在一行中打印集合的相似性,以百分比形式精确到小数点后1位。 

思路分析:

用vector 存储 多个set,若求 a,b集合的相似性,遍历a的每个元素,在b中查找,存在为即为公共元素,不存在即为不同元素。


#include <iostream>
#include <set>
#include <vector>
using  namespace  std;

int main(){
    int n,m,m1,k,a,b;
    cin>> n;  //输入集合的个数
    vector<set<int>> v(n);   // 创建动态数组
    for(int i=0;i<n;i++){
        cin>>m;              // 输入每个集合元素的个数
        set<int> s;
        for(int j=0;j<m;j++){  // 输入每个集合的元素
            cin >>m1;
            s.insert(m1);
        }
        v[i]=s;
    }
    cin >> k;   //输入查询的次数
    for(int i=0;i<k;i++){
        cin >> a>>b; // 输入需要查询的两个集合
        int nc=0,nt=v[b-1].size();   // nc为公共元素的个数,nt两个集合不同元素的个数,初始值为b集合元素的个数
        for(auto it= v[a-1].begin();it!=v[a-1].end();it++){  // 遍历a的每个元素,在b中找,若在b中存在则nc+1,找不到则nt+1
            if(v[b-1].find(*it) ==v[b-1].end()){
                nt++;
            }
            else{
                nc++;
            }
        }
        double result;    //  相似度
        result = nc*1.0/nt *100;
        printf("%.1f\n",result);

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值