《算法筆記》6.2小節 問題 A: 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.

輸入

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.

輸出

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

樣例輸入

3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3

樣例輸出

50.0%
33.3%

思路:題目看了很久看不懂,找了好幾個題解纔看懂題意emmmm,首先輸入n,代表有n組集合(本題爲3組集合),找兩組集合的交集(NC)和並集(NT),輸入K,代表查詢K次(1 2 和 1 3表示分別查詢集合1、2和集合1、3

1.建立set數組存放集合

2.查詢集合x、y,cnum和tnum分別表示交集元素個數和並集元素個數。首先將tnum設爲集合y的元素個數,訪問集合x的元素,如果在集合y中能找到(使用find函數,如果返回不等於end),那麼交集個數+1,否則並集個數+1。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,m,t;
    set<int> a[51];

    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>m;
        for(int j=0;j<m;j++)
        {
            cin>>t;
            a[i].insert(t);
        }
    }

    int s;
    cin>>s;
    while(s--)
    {
        int x,y;
        cin>>x>>y;
        set<int>::iterator it;

        int cnum=0,tnum=a[y-1].size();        //cnum爲交集,tnum爲並集
        for(it=a[x-1].begin();it!=a[x-1].end();it++)
        {
            if(a[y-1].find(*it)!=a[y-1].end())  //如果在y中能找到,則交集++
                cnum++;
            else               //如果找不到,說明這個數字是x和y中不相同的數字,並集++
                tnum++;
        }
        printf("%.1f%%\n",cnum*100.0/tnum);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章