feizhu0130 @ 2023-12-27 20:45:51
#include<bits/stdc++.h>
using namespace std;
struct node
{
string name;
int yu,shu,ying,zong;
};
bool cmp(node q,node h)
{
if(q.zong>=h.zong) return q.zong<h.zong;
else return h.zong<q.zong;
}
node a[1005];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i].name>>a[i].yu>>a[i].shu>>a[i].ying;
a[i].zong=a[i].yu+a[i].shu+a[i].ying;
}
sort(a+1,a+1+n,cmp);
cout<<a[1].name<<" "<<a[1].yu<<" "<<a[1].shu<<" "<<a[1].ying<<" ";
return 0;
}
by ShiRoZeTsu @ 2023-12-27 20:54:38
@feizhu0130
return q.zong > h.zong;
按照你的写法,那么你的 cmp
函数返回值就永远都是 false
了,这个不对。
id
来保证先后顺序。所以正确的 cmp
的写法是:
bool cmp(node q, node h) {
if(q.zong != h.zong) return q.zong > h.zong;
return q.id < h.id;
}
by Lcx_AK_IOI @ 2023-12-27 20:55:14
这、
if(q.zong>=h.zong) return q.zong<h.zong;
by feizhu0130 @ 2023-12-27 21:08:30
感谢大佬纠错(^W^)!!!
by feizhu0130 @ 2023-12-27 21:10:13
主要是学结构体排序时没学好
by ShiRoZeTsu @ 2023-12-27 21:13:42
@feizhu0130 小于号就从小到大排,大于号就从大到小排,直接返回就 OK 的。
by feizhu0130 @ 2023-12-27 21:14:24
二次求助,90分,求纠错(QWQ)
#include<bits/stdc++.h>
using namespace std;
struct node
{
string name;
int yu,shu,ying,zong,id;
};
bool cmp(node q,node h)
{
if(q.zong!=h.zong) return q.zong>h.zong;
else return q.id<h.id;
}
node a[10005];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i].name>>a[i].yu>>a[i].shu>>a[i].ying;
a[i].zong=a[i].yu+a[i].shu+a[i].ying;
}
sort(a+1,a+1+n,cmp);
cout<<a[1].name<<" "<<a[1].yu<<" "<<a[1].shu<<" "<<a[1].ying<<" ";
return 0;
}
by ShiRoZeTsu @ 2023-12-27 21:16:09
@feizhu0130 这个 id 的意思是输入的顺序,因为当相同分数出现时要保证输出最前面那个,也就是 id 最小的。
孩子,id 你得初始化呀 /doge
可以参考我的
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e3 + 5;
int n;
struct node {
string name;
int val, id, x, y, z;
} a[maxn];
int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i].name >> a[i].x >> a[i].y >> a[i].z;
a[i].val = a[i].x + a[i].y + a[i].z;
//看这里
a[i].id = i;
}
sort(a+1, a+1+n, [](node x, node y) {
if(x.val != y.val) return x.val > y.val;
return x.id < y.id;
}) ;
cout << a[1].name << ' ' << a[1].x << ' ' << a[1].y << ' ' << a[1].z << '\n';
return 0;
}
by feizhu0130 @ 2023-12-27 21:18:28
十分感谢,AC了