参考:
https://blog.youkuaiyun.com/xylon_/article/details/81181375
1 set 是集合, 无重复元素,并且 set 帮你排序。
集合的一个性质是互异。也就是说 ,set 里面的元素没有重复的,
#include<iostream>
#include<set>
#include<algorithm>
using namespace std;
struct ac
{
string name;
int sum,p; //sum记录不同标签的数量,p记录标签总数
}a[105];
bool cmp(ac x,ac y)
{
if(x.sum==y.sum)
return x.p<y.p;
return x.sum>y.sum;
}
int main()
{
int t,n,i,x;
cin>>t;
for(i=0;i<t;i++)
{
cin>>a[i].name;
cin>>n;
a[i].p=n;
set<int>s;
while(n--)
{
cin>>x;
s.insert(x);
}
a[i].sum=s.size();
s.clear();
}
sort(a,a+t,cmp);
if(t>=3)
{
cout<<a[0].name;
for(i=1;i<3;i++)
cout<<" "<<a[i].name;
}
else if(t==2)
{
cout<<a[0].name;
for(i=1;i<2;i++)
cout<<" "<<a[i].name;
cout<<" "<<"-"<<endl;
}
else if(t==1)
{
cout<<a[0].name;
cout<<" "<<"-"<<" "<<"-"<<endl;
}
else
cout<<"-"<<" "<<"-"<<" "<<"-"<<endl;
return 0;
}
找到一个更秀的 直接把结构体放进set 里面,按照结构体内部排序规则
#include <iostream>
#include <string>
#include <set>
using namespace std;
struct peo
{
string name;
int sum;
int cnt;
friend bool operator<(const peo &p1, const peo &p2)
{
//倒序排
if (p1.cnt == p2.cnt)
return (p1.sum*1.0 / p1.cnt) < (p2.sum*1.0 / p2.cnt);
return p1.cnt > p2.cnt;
}
};
int main()
{
set<peo> sp;
int n; cin >> n;
string tname;
for (int i = 0; i < n; ++i) {
peo p;
cin >> tname;
p.name = tname;
int m; cin >> m;
p.sum = m;
set<int> s;
for (int j = 0; j < m; ++j) {
int x; cin >> x;
s.insert(x);
}
p.cnt = s.size();
sp.insert(p);
}
set<peo>::iterator it=sp.begin();
int flag = 0;
for (; it != sp.end(); ++it) {
if (flag < 3) {
if (flag)
cout << " ";
cout << it->name;
++flag;
}
else
break;
}
for (; flag < 3; ++flag) {
cout << " " << "-";
}
system("pause");
return 0;
}
看了题解自己练习 set 的时候出的问题,
我想把五个人全输出来,但是只有3个人
#include<bits/stdc++.h>
using namespace std;
struct REN
{
string name;
int cou;
int sum;
bool operator< ( const REN &a ) const{
return cou>a.cou;
}
};
后来才知道,当 cou == a.cou 的时候 这个结构体的变量被 set 踢出来了。
终于
最后能输出五个人了
#include<bits/stdc++.h>
using namespace std;
struct REN
{
string name;
int cou;
int sum;
bool operator< ( const REN &a ) const{
if(cou!=a.cou)
return cou>a.cou;
else
return sum<a.sum;
}
};
set<REN> set_1;
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
REN re;
string kk;
cin>>kk;
re.name=kk;
int k; cin>>k;
set<int>set_2;
set_2.clear();
for(int j=0;j<k;j++)
{
int a; cin>>a;
set_2.insert(a);
}
re.cou=set_2.size();
re.sum=k;
set_1.insert(re);
// cout<<"shi ta "<<re.name<<" "<<re.cou<<endl;
}
for(set<REN>::iterator it=set_1.begin();it!=set_1.end();it++ )
{
cout<<it->name<<" "<<it->cou<<endl;
}
return 0;
}