80分!!cmp有问题但不知道错在哪里

P1093 [NOIP2007 普及组] 奖学金

yuanzhangyi @ 2024-07-23 22:52:04

#include<bits/stdc++.h>
using namespace std;
struct student{
    int yw,sx,yy,sum;
    int id;
};
bool cmp(student a,student b){
    if(a.sum==b.sum) {
        if (a.yw==b.yw){
            if(a.id<b.id){
                return a.id;}
            else return b.id;   
            }
            if(a.yw>b.yw){
                return a.yw;
            }
            else return b.yw ;
        }
    else return a.sum>b.sum;
}
int main(){
    int n;
    cin>>n;
    student s[n];
    for(int i=0;i<n;i++){
        s[i].id=i+1;
        cin>>s[i].yw>>s[i].sx>>s[i].yy;
        s[i].sum=s[i].yw+s[i].sx+s[i].yy;
    }
    sort(s,s+n,cmp);
    for(int m=0;m<5;m++){
        cout<<s[m].id<<' '<<s[m].sum <<endl;
    }
    return 0;
}                                                                                        

by Begemot @ 2024-07-23 23:01:05

if(a.yw>b.yw){的判断写在if (a.yw==b.yw){嵌套里面了


by HeartBeast @ 2024-07-23 23:33:56

#include<bits/stdc++.h>
using namespace std;
struct student{
    int yw,sx,yy,sum;
    int id;
};
bool cmp(student a,student b)
{
    if(a.sum==b.sum) {
        if (a.yw==b.yw)
            return a.id<b.id;
        return a.yw>b.yw;   
    }
    return a.sum>b.sum;
}
int main()
{
    int n;
    cin>>n;
    student s[n];
    for(int i=0;i<n;i++){
        s[i].id=i+1;
        cin>>s[i].yw>>s[i].sx>>s[i].yy;
        s[i].sum=s[i].yw+s[i].sx+s[i].yy;
    }
    sort(s,s+n,cmp);
    for(int m=0;m<5;m++){
        cout<<s[m].id<<' '<<s[m].sum <<endl;
    }
    return 0;
}

cmp有问题,sort的cmp不需要if判断可以直接将return a<b之类当if用

你程序括号是不是写错了啊


by HeartBeast @ 2024-07-23 23:34:39

@yuanzhangyi


by yuanzhangyi @ 2024-07-25 22:06:49

谢大佬!!!(已关)


|