题目
给定两个整数集合,它们的相似度定义为:N c /N t ×100%。其中N c
是两个集合都有的不相等整数的个数,N t 是两个集合一共有的不相等整数的个数。你的任务就是计算任意一对给定集合的相似度。
输入格式:
输入第一行给出一个正整数N(≤50),是集合的个数。随后N行,每行对应一个集合。每个集合首先给出一个正整数M(≤10 4 ),是集合中元素的个数;然后跟M个[0,10 9 ]区间内的整数。
之后一行给出一个正整数K(≤2000),随后K行,每行对应一对需要计算相似度的集合的编号(集合从1到N编号)。数字间以空格分隔。
输出格式:
对每一对需要计算的集合,在一行中输出它们的相似度,为保留小数点后2位的百分比数字。
输入样例:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3
输出样例:
50.00%
33.33%
讲解
这里的N c 是两个集合都有的不相等整数的个数:两个去重后相同的整数数目
这里的N t是两个集合一共有的不相等整数的个数:两个集合总个数,相同的和不相同的,但是记住相同的只计算一遍。难搞
代码
#include <iostream>
#include <set>
using namespace std;
set<int> se[55]; // 用集合来存储每个集合中的数字
int main()
{
int n,k,tem;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&k);
for(int j=0;j<k;j++)
{
scanf("%d",&tem);
se[i].insert(tem);
}
}
scanf("%d",&k);
int a,b,same=0;
int na,nb;
for(int i=0;i<k;i++)
{
same = 0;
scanf("%d %d",&a,&b);
a= a-1;
b = b-1;
na = se[a].size(); // a中集合的数量
nb = se[b].size(); // b中集合的数量
/*
1.这里的auto相当于变量,根据=后面的东西自动定义。
2.但是需要修改工具编译选项里面的g++
3.工具->编译选项->程序->g++:g++.exe 改为:g++ -std=c++11就可以使用auto了。
4.有另外一种方法 set<int>:: iterator it;可以直接定义一个it
*/
for (auto it=se[a].begin();it != se[a].end();it++)
{
// 找到了 相同的数字
if(se[b].count(*it)==1)
same ++;
}
printf("%.2lf%%\n",1.0*same/(na+nb-same)*100);
}
return 0;
}
set
1.工具->编译选项->程序->g++:g++.exe 改为:g++ -std=c++11就可以使用auto了。
set集合是c++ stl库中自带的一个容器,set具有以下两个特点:
1、set中的元素都是排好序的
2、set集合中没有重复的元素
常用操作:
begin() 返回set容器的第一个元素的地址
end() 返回set容器的最后一个元素地址
clear() 删除set容器中的所有的元素
empty() 判断set容器是否为空
max_size() 返回set容器可能包含的元素最大个数
size() 返回当前set容器中的元素个数
erase(it) 删除迭代器指针it处元素
insert(a) 插入某个元素
count(a) 找到a元素就返回1,没找到就返回0
set<int>::iterator it; 可不用修改编译器选项
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> s;
s.insert(5);
s.insert(4);
s.insert(3);
s.insert(-2);
cout << s.size() <<endl;
if(s.count(5)==0)
cout<<"not Find 5"<<endl;
else
cout<<"find 5"<<endl;
s.erase(5); // 删除5元素
if(s.count(5)==0)
cout<<"nof Find 5"<<endl;
else
cout<<"find 5"<<endl;
cout << s.size() <<endl;
// 它是顺序排列的。
for(auto it=s.begin();it != s.end();it++)
{
cout<<*it<<' ';
}
cout<<endl;
return 0;
}