90分求助!!!!!!!!!!

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

keda2761 @ 2023-03-12 14:16:04

#include<bits/stdc++.h>
using namespace std;
struct student{
    string name;
    int maths,chinese,english;
}a[5005];
bool cmp(student a,student b){
    return a.maths+a.english+a.chinese<b.maths+b.english+b.chinese;
}
int n,number,maxi=0,sum;
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i].name>>a[i].maths>>a[i].english>>a[i].chinese; 
    }
    sort(a,a+n,cmp);
    for(int i=0;i<n;i++){
        sum=a[i].maths+a[i].english+a[i].chinese;
        if(sum>maxi){
            maxi=sum;
            number=i;
        }
    }
    cout<<a[number].name<<' '<<a[number].maths<<' '<<a[number].english<<' '<<a[number].chinese;
    return 0;
}

by NTFS @ 2023-03-12 14:39:48

@zhouyilin 少了一种情况 “如果有多个总分相同的学生,输出靠前的那位。”


by keda2761 @ 2023-03-12 14:41:04

@NTFS 我考虑了的


by NTFS @ 2023-03-12 14:46:46

@zhouyilin 排序时候没有考虑


by NTFS @ 2023-03-12 14:49:43

总分不相等时返回大的
总分相等时返回排名靠前的
应该是在cmp里对靠前进行排序 而不是排序后才对靠前的判断


by keda2761 @ 2023-03-12 14:50:43

我重新写了一段代码:

#include<bits/stdc++.h>
using namespace std;
struct{
    string name;
    int a,b,c;
}student[1001]; 
int main(){
    int n,maxi=-11,sum,x;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>student[i].name>>student[i].a>>student[i].b>>student[i].c;
    }
    for(int i=0;i<n;i++){
        sum=student[i].a+student[i].b+student[i].c;
        if(maxi<sum){
            maxi=sum;
            x=i;
        }
    }
    cout<<student[x].name<<' '<<student[x].a<<' '<<student[x].b<<' '<<student[x].c;
    return 0;
}

by keda2761 @ 2023-03-12 14:51:48

AC了,谢谢老兄的指导!!!?‍?‍?‍


by NTFS @ 2023-03-12 14:59:31

struct student{
    string name;
    int num;//顺序
    int maths,chinese,english;
    int s;//总分,方便的写法
}a[5005];
bool cmp(student a,student b){
    if(a.s!=b.s)return a.s>b.s;//不想等时
    else return a.num<b.num;//特别判断
}
int n,sum;//就这些
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i].name>>a[i].maths>>a[i].english>>a[i].chinese; 
        a[i].s=a[i].maths+a[i].english+a[i].chinese;
        a[i].num=i;
    }
    sort(a,a+n,cmp);
    cout<<a[0].name<<' '<<a[0].maths<<' '<<a[0].english<<' '<<a[0].chinese;//排序后最厉害的在最前
    return 0;
}

by NTFS @ 2023-03-12 14:59:58

@zhouyilin 好


by 1ooper @ 2023-05-03 23:05:41

#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
struct node{
    long long x,w,s,y,ans;
    string na;
}k[N];
bool cmp(node a,node z){
    if(a.ans==z.ans)return a.x<z.x;
    return a.ans>z.ans;
}
int main(){
    long long n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>k[i].na>>k[i].w>>k[i].s>>k[i].y;
        k[i].ans=k[i].w+k[i].s+k[i].y;
        k[i].x=i;
    }
    sort(k+1,k+1+n,cmp);
    cout<<k[1].na<<" "<<k[1].w<<" "<<k[1].s<<" "<<k[1].y;

}

|