自定义 cmp() 比较函数
#include<cstdio> #include<algorithm> using namespace std; struct Student{ int id, a, b, c ,sum; //学号,语,数,英,总分 }stu[300]; bool cmp(const Student &s1, const Student &s2){ if(s1.sum==s2.sum){ if(s1.a==s2.a) return s1.id<s2.id; return s1.a>s2.a; } return s1.sum>s2.sum; } int main(){ int n; scanf("%d",&n); for(int i=0; i<n; i++){ scanf("%d %d %d", &stu[i].a, &stu[i].b, &stu[i].c); stu[i].id = i+1 ; stu[i].sum = stu[i].a+stu[i].b+stu[i].c; } sort(stu,stu+n, cmp); for(int i=0;i<5;i++){ printf("%d %d\n", stu[i].id, stu[i].sum); } return 0; }
重载运算符。因为sort默认升序,重载<
#include<cstdio> #include<algorithm> using namespace std; struct Student{ int id, a, b, c ,sum; //学号,语,数,英,总分 bool operator < (const Student &x)const{ return (sum==x.sum && a==x.a && id<x.id ) || (sum==x.sum && a>x.a) || (sum>x.sum); } }stu[300]; int main(){ int n; scanf("%d",&n); for(int i=0; i<n; i++){ scanf("%d %d %d", &stu[i].a, &stu[i].b, &stu[i].c); stu[i].id = i+1 ; stu[i].sum = stu[i].a+stu[i].b+stu[i].c; } sort(stu,stu+n); for(int i=0;i<5;i++){ printf("%d %d\n", stu[i].id, stu[i].sum); } return 0; }
题目只要前五名
使用选择排序,选出前五名,算法停止
#include<cstdio> #include<algorithm> using namespace std; struct Student{ int id, a, b, c ,sum; //学号,语,数,英,总分 bool operator > (const Student &x)const{ return (sum==x.sum && a==x.a && id<x.id ) || (sum==x.sum && a>x.a) || (sum>x.sum); } }stu[300]; int main(){ int n; scanf("%d",&n); for(int i=0; i<n; i++){ scanf("%d %d %d", &stu[i].a, &stu[i].b, &stu[i].c); stu[i].id = i+1 ; stu[i].sum = stu[i].a+stu[i].b+stu[i].c; } for(int i=0; i<5; i++){ for(int j=i+1; j<n; j++) if(stu[j]>stu[i]) swap(stu[i], stu[j]); } for(int i=0;i<5;i++){ printf("%d %d\n", stu[i].id, stu[i].sum); } return 0; }
0.0分
0 人评分
WU-printf基础练习2 (C++代码)浏览:2061 |
完数 (C语言代码)浏览:757 |
1009题解浏览:802 |
字符逆序 (C语言代码)浏览:506 |
1051(奇了怪了)浏览:747 |
大神老白 (C语言代码)浏览:637 |
字符串比较 (C语言代码)浏览:770 |
简单的事情 (C语言代码)浏览:679 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:620 |
简单的a+b (C语言代码)浏览:491 |