#3#10报错,求大佬!!

P1093 [NOIP2007 普及组] 奖学金

岗岗dsg @ 2021-03-16 15:17:59

#include<stdio.h>
struct st {
    int math;
    int chi;
    int eng;
    int sum;
    int num;
};
int main() {
    int n;
    struct st s[233],t;
    scanf("%d", &n);
    for (int i = 1;i <= n;i++) {
        scanf("%d%d%d", &s[i].chi, &s[i].math, &s[i].eng);
        s[i].sum = s[i].chi + s[i].eng + s[i].math;
        s[i].num = i;
    }
    for(int i=0;i<n;i++) 
        for (int j = 1;j <= n - i;j++) {
            if (s[j].sum < s[j + 1].sum) {
                t = s[j];
                s[j] = s[j + 1];
                s[j + 1] = t;
            }
            if (s[j].sum == s[j + 1].sum) {
                if (s[j].chi < s[j + 1].chi) {
                    t = s[j];
                    s[j] = s[j + 1];
                    s[j + 1] = t;
                }
                else if (s[j].chi == s[j + 1].chi) {
                    if (s[j].num > s[j + 1].num) {
                        t = s[j];
                        s[j] = s[j + 1];
                        s[j + 1] = t;
                    }
                }
            }
        }
    for (int i = 1;i <= 5;i++) printf("%d %d\n", s[i].num, s[i].sum);
    return 0;
}

by LYqwq @ 2021-03-16 21:22:29

建议你使用sort排序


by LYqwq @ 2021-03-16 21:23:09

而且所有交换都用swap函数


by LYqwq @ 2021-03-16 21:32:39

你这代码有点乱,建议修改一下代码风格,学一学STL和c/c++内置函数

顺便贴上我的代码:

#include <iostream>
#include <algorithm>
using namespace std;

class STU{
    public:
        // 学号,语文,数学,英语,总成绩
        int id,yw,sx,yy,num;
}stu[305];

bool cmp(STU a,STU b){
    if(a.num!=b.num){
        return a.num>b.num;
    }else if(a.yw!=b.yw){
        return a.yw>b.yw;
    }
    return a.id<b.id;
}

int main(){
    int n;
    cin >> n;
    for(int i=0; i<n; i++){
        cin >> stu[i].yw >> stu[i].sx >> stu[i].yy;
        stu[i].id = i+1;
        stu[i].num = stu[i].yw+stu[i].sx+stu[i].yy;
    }
    sort(stu,stu+n,cmp);
    for(int i=0; i<5; i++){
        cout << stu[i].id << " " << stu[i].num << endl;
    }
    return 0;
}

by LYqwq @ 2021-03-16 21:37:33

s数组空间开小了


|