Set Similarity (25)

来源:互联网 发布:怎样增加淘宝访客量 编辑:程序博客网 时间:2024/06/05 03:29

题目描述

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.

输入例子:

33 99 87 1014 87 101 5 877 99 101 18 5 135 18 9921 21 3

输出例子:

50.0%33.3%

我的代码(C++):

#include<iostream>#include<set>using namespace std;int main(){    set<int> s[50];    set<int>::iterator it;    int x,y,z,n,m1,m2,i;    scanf("%d",&x);    for(i=0;i<x;i++)    {        scanf("%d",&y);        while(y--)        {            scanf("%d",&z);            s[i].insert(z);        }    }    scanf("%d",&n);    while(n--)    {        scanf("%d%d",&m1,&m2);        int cnt=0;        for(it=s[m1-1].begin();it!=s[m1-1].end();it++)        {            if(s[m2-1].find(*it)!=s[m2-1].end()) cnt++;        }        double sum=s[m1-1].size()+s[m2-1].size()-cnt;        printf("%.1f%%\n",cnt/sum*100);    }    return 0;}

我的代码(Java):

import java.util.HashSet;import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner In=new Scanner(System.in);int x=In.nextInt();HashSet[] s=new HashSet[x];for(int i=0;i<x;i++){int y=In.nextInt();s[i]=new HashSet<Integer>(y);for(int j=0;j<y;j++){int z=In.nextInt();s[i].add(z);}}int n=In.nextInt();for(int i=0;i<n;i++){int m1=In.nextInt();int m2=In.nextInt();int cnt=0;HashSet<Integer> s1=s[m1-1];HashSet<Integer> s2=s[m2-1];for(Integer integer:s2){if(s1.contains(integer)) cnt++;}double sum=s1.size()+s2.size()-cnt;System.out.printf("%.1f%%\n",cnt/sum*100);}}}

原创粉丝点击