PAT-A 真题 – 1063 Set Similarity

发布于 / PAT-甲级 / 0 条评论

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 (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.

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%

题目大意:集合相似度,定义Nc为两个集合公共元素个数,Nt为两个集合总共元素个数,集合相似度定义为Nc/Nt * 100.0%

这道题需要使用set存储集合,如果使用vector或者数组,要记得去重。

Nc的计算用set::find()函数即可,Nt的计算可以用两个集合元素总数量-公共元素数量

#include <bits/stdc++.h>
using namespace std;

int main(){
  int cnt;
  scanf("%d", &cnt);
  vector<set<int> > V(cnt + 1);
  for(int i = 1; i <= cnt; i++){
    int icnt;
    scanf("%d", &icnt);
    while(icnt--){
      int t;
      scanf("%d", &t);
      V[i].insert(t);
    }
  }
  scanf("%d", &cnt);
  while(cnt--){
    int a, b;
    scanf("%d %d", &a, &b);
    int Nc = 0, Nt = V[b].size();
    for(auto it : V[a]){
      if(V[b].find(it) != V[b].end()) Nc++;
      else Nt++;
    }
    printf("%.01f%%\n", 100.0 * Nc / Nt);
  }
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题 – 1063 Set Similarity
目前还没有评论,快来抢沙发吧~