90分求助

P5740 【深基7.例9】最厉害的学生

WEICY123 @ 2024-05-26 20:31:37

#include<bits/stdc++.h>
using namespace std;
int n,ans;
struct cj{
    string f;
    int b,c,d,z;
}a[10001];
bool cmp(cj x,cj y){
    return x.z>y.z;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].f>>a[i].b>>a[i].c>>a[i].d;
        a[i].z+=a[i].b+a[i].c+a[i].d;
    }
    sort(a+1,a+n+1,cmp);
    cout<<a[1].f<<" "<<a[1].b<<" "<<a[1].c<<" "<<a[1].d;
}

by Qiu101029 @ 2024-05-26 20:38:54

@WEICY123 如果有多个总分相同的学生,输出靠前的那位(题目中的)

sort函数可能改变顺序


by WEICY123 @ 2024-05-27 12:52:03

@Qiu101029 感谢你的提醒,but我只会排序


by Qiu101029 @ 2024-05-28 21:56:08

@WEICY123 改一下结构体和cmp函数

#include<bits/stdc++.h>
using namespace std;
int n,ans;
struct cj{
    string f;
    int b,c,d,z,id;//id是输入顺序
}a[10001];
bool cmp(cj x,cj y){
    if(x.z!=y.z) return x.z>y.z;
    else return x.id<y.id;//把输入靠前的排在前面
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].f>>a[i].b>>a[i].c>>a[i].d;
        a[i].z+=a[i].b+a[i].c+a[i].d;
        a[i].id=i;//记录输入顺序
    }
    sort(a+1,a+n+1,cmp);
    cout<<a[1].f<<" "<<a[1].b<<" "<<a[1].c<<" "<<a[1].d;
}

by WEICY123 @ 2024-05-29 11:49:40

@Qiu101029 感谢


by Crisp_lrc @ 2024-06-07 16:30:54

@Qiu101029 感谢,我也是这个问题,记录一下输入顺序就好了!


|