求助大佬

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

_CCCCcccc @ 2024-12-21 10:31:25

#include<iostream>
using namespace std;
struct Student {
    string name;
    int Chinese;
    int Math;
    int English;
}student[1000];
int main() {
    int n;
    int a[1000];
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> student[i].name >> student[i].Chinese >> student[i].Math >> student[i].English;
    }
    for (int i = 0; i < n; i++) {
        a[i] = student[i].Chinese + student[i].Math + student[i].English;
    }
    for (int i = 0; i < n - 1; i++) {
        for (int j = i+1; j < n; j++) {
            if (a[i] < a[j]) { 
                swap(student[i].name, student[j].name);
                swap(student[i].Chinese, student[j].Chinese);
                swap(student[i].Math, student[j].Math);
                swap(student[i].English, student[j].English);
            }
        }
    }
    cout << student[0].name << " " << student[0].Chinese <<" " <<student[0].Math << " "<<student[0].English;
    return 0;
}

by 20080904weiyuhang @ 2024-12-21 10:46:30

你第21行到25行把结构体都换了,为什么不把 a[i] 和 a[j] 换了呢?


by dendky @ 2024-12-21 10:47:36

@_CCCCcccc

#include<bits/stdc++.h>
using namespace std;
struct Student {
    string name;
    int Chinese;
    int Math;
    int English;
}student[1000];
int a[1000];
int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin>>student[i].name>>student[i].Chinese>>student[i].Math>>student[i].English;
    }
    for (int i = 0; i < n; i++) {
        a[i] = student[i].Chinese + student[i].Math + student[i].English;
    }
    for (int i = 0; i < n - 1; i++) {
        for (int j = i+1; j < n; j++) {
            if (a[i] < a[j]) { 
                swap(student[i].name, student[j].name);
                swap(student[i].Chinese, student[j].Chinese);
                swap(student[i].Math, student[j].Math);
                swap(student[i].English, student[j].English);
                swap(a[i], a[j]);//就是这个
            }
        }
    }
    cout<<student[0].name<<" "<<student[0].Chinese<<" "<<student[0].Math<<" "<<student[0].English;
    return 0;
}

by _CCCCcccc @ 2024-12-21 11:05:42

@20080904weiyuhang感谢


by _CCCCcccc @ 2024-12-21 11:06:13

@dendky感谢


|