1. 程式人生 > >【PAT】1063. Set Similarity (25)【set容器的使用】

【PAT】1063. Set Similarity (25)【set容器的使用】

題目描述

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.

翻譯:給你兩個整數集合,他們之間的相似度被定義為Nc/Nt*100%,NC是兩個集合之間共有的特定數字,Nt為兩個集合中不同數字的總數。你的任務是計算給定一對集合的相似度。

INPUT FORMAT

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.

翻譯:每個輸入檔案包含一組測試資料。對於每組輸入資料,第一行包括一個正整數N(<=50)代表總集合數。接著N行,每行給出一個集合,首先是M(<=10^4),接著是M個在{0-10^9}範圍內的整數。在集合輸入完畢後,是一個正整數K(<=2000),跟著K行查詢。每個查詢包含一對集合編號(集合被編號為1-N)。一行內所有數字之間用空格隔開。

OUTPUT FORMAT

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容器了。兩個集合中交集的個數需要遍歷一個集合,然後用count()函式判斷是否在另一個集合中出現; 並集的個數為兩個集合的size()之和減去交集數。輸出時記得轉換為百分比輸出。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<set> 
#include<algorithm>
#define INF 99999999
using namespace std;
set<int> st[60];
set<int>::iterator it;
int N,K;
int main(){
    scanf("%d",&N);
    int M;
    for(int i=1;i<=N;i++){
        scanf("%d",&M);
        int a;
        for(int j=0;j<M;j++){
            scanf("%d",&a);
            st[i].insert(a);
        }
    }
    scanf("%d",&K);
    int p,q;
    for(int i=0;i<K;i++){
        int sum,common=0;
        scanf("%d%d",&p,&q);
        for(it=st[p].begin();it!=st[p].end();it++){
            if(st[q].count(*it))common++;
        }
        sum=st[p].size()+st[q].size()-common;
        double ans=common*1.0/sum;
        ans*=100;
        printf("%.1lf%%\n",ans);
    }
    return 0;
}