目录
题目:PAT 1063 Set Similarity
解题思路:
自己由于英文不好,在读题时,不明白题意,但大体了解它是要求Nc与Nt的比值,但Nc和Nt具体表示什么含义,自己不清楚,上网查了一下这两个的含义,Nc表示两个集合的差集,Nt表示两个集合的并集,题目需要我们计算Nc/Nt,就是要求我们计算Nc.size(Nc数字个数)/Nt.size(数字个数),对于集合类型题目,在此处使用set进行解决,非常的方便(题目也是主要考察这一块知识),同时自己在思考如何计算它们的差集和并集时,发现了一个规律,就是Nc.size+Nt.size=X.size+B.size,计算差集其实是不方便的,但是计算并集我们利用set可以自动去重这一特性可以非常容易计算出Nt.size,Nc.size也自然而然可以计算出了。
代码版本1
#include<iostream>
#include<algorithm>
#include<set>
#include<cstdio>
using namespace std;
const int P = 52;
int main(){
int N,M;//集合个数N,每个集合的数字数
set<int> sInt[P];
scanf("%d", &N);
for (int i = 1; i <= N; i++)
{
scanf("%d",&M);
for (int j = 0; j < M; j++)
{
int num;
scanf("%d",&num);
sInt[i].insert(num);
}
}
//查询
int nQuery,n1Set,n2Set;
scanf("%d", &nQuery);
for (int i = 0; i < nQuery; i++)
{
scanf("%d %d", &n1Set, &n2Set);
//计算并集
set<int> temp;//生成一个临时set
temp = sInt[n1Set];
for (auto i : sInt[n1Set])//将两个set都插入到temp中,会超时
{
temp.insert(i);//将sInt[n1Set中的元素加入到temp中]
}
for (auto i : sInt[n2Set])
{
temp.insert(i); //将sInt[n1Set中的元素加入到temp中]
}
//计算相似率
int sizeT = temp.size();
int sizeC = (sInt[n1Set].size() + sInt[n2Set].size())-sizeT;
printf("%.1f%%", (float)sizeC / sizeT*100);
if (i+1!=nQuery)
{
printf("\n");
}
}
//system("pause");
return 0;
}
上面是自己的第一次提交代码,最后一个测试点,出现了运行超时,自己分析后,问题应该在于对于数据量比较大的情况下,如果对Temp实施了两轮插入,估测是算法复杂度过高,insert方法的复杂度为,而for循环方法为n,则总的复杂度为,且执行两轮,则耗费时间过长,导致运行超时,因此,采用生成temp后,直接将其中一个数据集赋值给它,另一个数据集对它插入,以减少运行时间,只需一轮即可获得并集。
代码版本2
#include<iostream>
#include<algorithm>
#include<set>
#include<cstdio>
using namespace std;
const int P = 52;
int main(){
int N,M;//集合个数N,每个集合的数字数
set<int> sInt[P];
scanf("%d", &N);
for (int i = 1; i <= N; i++)
{
scanf("%d",&M);
for (int j = 0; j < M; j++)
{
int num;
scanf("%d",&num);
sInt[i].insert(num);
}
}
//查询
int nQuery,n1Set,n2Set;
scanf("%d", &nQuery);
for (int i = 0; i < nQuery; i++)
{
scanf("%d %d", &n1Set, &n2Set);
//计算并集
set<int> temp;//生成一个临时set
temp = sInt[n1Set];
for (auto i : sInt[n2Set])
{
temp.insert(i); //将sInt[n1Set中的元素加入到temp中]
}
//计算相似率
int sizeT = temp.size();
int sizeC = (sInt[n1Set].size() + sInt[n2Set].size())-sizeT;
printf("%.1f%%", (float)sizeC / sizeT*100);
if (i+1!=nQuery)
{
printf("\n");
}
}
//system("pause");
return 0;
}