PAT (Advanced Level) Practice - 1063 Set Similarity (25 分)

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%

#include <stdio.h>
#include <string.h>
#define nMAX 50
#define mMAX 10000
void quicksort(int a[],int lo,int hi);  //快排
void duplicate(int a[],int n);          //去重(有序数组)(重复元素置为-1 并不真的删除)
int main(){
    int n,m,t[nMAX+1][mMAX+1],i,j,k,a,b,cnt1,cnt2;
    scanf("%d",&n);
    memset(t,0,sizeof(t));
    for(i=1;i<=n;i++){
        scanf("%d",&t[i][0]);
        for(j=1;j<=t[i][0];j++) scanf("%d",&t[i][j]);
        quicksort(t[i],1,t[i][0]+1);
        duplicate(t[i],t[i][0]+1);
    }
    scanf("%d",&m);
    for(i=0;i<m;i++){
        scanf("%d %d",&a,&b);
        j=k=1;
        cnt1=cnt2=0;
        while(j<=t[a][0] && k<=t[b][0]){
            if(t[a][j]==-1) j++;
            else if(t[b][k]==-1) k++;
            else if(t[a][j]<t[b][k]){
                j++;
                cnt2++;
            }
            else if(t[a][j]>t[b][k]){
                k++;
                cnt2++;
            }
            else{
                j++;
                k++;
                cnt1++;
                cnt2++;
            }
        }
        while(j<=t[a][0]){
            if(t[a][j++]!=-1) cnt2++;
        }
        while(k<=t[b][0]){
            if(t[b][k++]!=-1) cnt2++;
        }
        if(cnt2!=0) printf("%.1lf%%\n",100.0*cnt1/cnt2);
        else printf("0.0%%\n");
    }
    return 0;
}
void quicksort(int a[],int lo,int hi){
    int n=hi-lo,i=lo,j=hi-1,t;
    if(n<=1) return;
    else{
        t=a[lo];
        while(i<j){
            while(i<j && a[j]>=t) j--;  //因为有重复元素 所以必须用a[j]>=t 而不能用a[j]>t 会死循环
            a[i]=a[j];
            while(i<j && a[i]<=t) i++;
            a[j]=a[i];
        }
        a[i]=t;
        quicksort(a,lo,i);
        quicksort(a,i+1,hi);
    }
}
void duplicate(int a[],int n){
    int i=1,j=2;
    while(j<n){
        while(j<n && a[i]==a[j]) a[j++]=-1;
        i=j++;
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页