1063. Set Similarity (25)

the problem is from PAT,which website is http://pat.zju.edu.cn/contests/pat-a-practise/1063

At first, i decide use a for loop to get the intersection, which time complexity is

O(n * log(n)) ,but it turned out that the result of one example is time running out. then i

searched the web and found there are one available in the “algorithm”file.

and the code is copied from another blog ,which url is http://blog.csdn.net/tiantangrenjian/article/details/16868399

#include <iostream>
#include <fstream>
#include <algorithm>        //set_intersection 函数
#include <iomanip>
#include <iterator>        //inserter函数
#include <set>
using namespace std;

#include <stdio.h>

int main()
{
    int n,m,in;
    cin>>n;
    set<int> *s = new set<int>[n];
    int i,j;
    for(i=0;i<n;i++)
    {
        cin>>m;
        for(j=0;j<m;j++)
        {
            cin>>in;
            s[i].insert(in);
        }
    }
    set<int> res;
    int k,a,b,nc,nt;
    cin>>k;
    for(i=0;i<k;i++)
    {
        cin>>a>>b;
        set_intersection(s[a-1].begin(),s[a-1].end(),s[b-1].begin(),s[b-1].end(),inserter(res,res.begin()));        //求集合交集
        nc = res.size();
        nt = s[a-1].size()+s[b-1].size()-nc;
        res.clear();
        cout<<setiosflags(ios::fixed)<<setprecision(1)<<(double)nc*100/nt<<"%"<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/maverick-fu/p/3977488.html