AC代码
#include<bits/stdc++.h>
using namespace std;
const int N = 310;
struct stu{
int id;
int cg;
int sg;
};
bool cmp(stu a,stu b){ ///按照题目要求写好排序函数
if(a.sg>b.sg)
return true;
else if(a.sg==b.sg&&a.cg>b.cg)
return true;
else if(a.sg==b.sg&&a.cg==b.cg&&a.id<b.id)
return true;
return false;
}
int n;
stu s[N];
int main(){
cin>>n;
for(int i=0;i<n;++i){
int x,y,z;
cin>>x>>y>>z;
s[i].id=i+1;
s[i].cg=x;
s[i].sg=x+y+z;
}
sort(s,s+n,cmp);
for(int i=0;i<5;++i)
cout<<s[i].id<<" "<<s[i].sg<<endl;
return 0;
}
重点就在于结构体的cmp函数的逻辑要写对,然后直接sort排序就好
y总的重载运算符写法
struct stu{
int id;
int cg;
int sg;
bool operator<(const stu &t) const{ ///主要是这里,逻辑很清楚
if(sg!=t.sg) return sg>t.sg;
if(cg!=t.cg) return cg>t.cg;
return id<t.id;
}
};