【PAT】B1015. 德才论(输入输出、sort、struct)
@(PAT)
链接:https://www.patest.cn/contests/pat-b-practise/1015
思路:
用结构体来存储每个学生的信息,然后按照题目信息将考生分成4类,分别按照规则排序,最后输出。
需要注意的地方:
1. algorithm里自带的sort函数非常好用,默认是按照数据降序排列,如果需要按照自己的规则排序,需要自己写compare函数作为sort函数的第三个输入参数。
2. 一个考生含有3种信息,用struct来存储信息是很好的选择。
3. 一开始用cin和cout来输入输出,有2个点会超时。cin和cout会比scanf和printf慢很多,所以刷题最好还是用scanf和printf吧。
scanf和printf用法总结可以参考下面这个博客:
https://www.cnblogs.com/michaeljunlove/p/3883717.html
(感谢原作者!)
My AC code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
struct Student {
int id;
int de;
int cai;
Student(int i, int d, int c) {
this->id= i;
this->de= d;
this->cai= c;
}
};
bool cmp(Student x, Student y) {
if ((x.de+ x.cai)!= (y.de+ y.cai)) return (x.de+ x.cai)> (y.de+ y.cai);
if (x.de!= y.de) return x.de> y.de;
return x.id< y.id;
}
void myPrint(vector<Student> v) {
for (int i= 0; i< v.size(); i++) {
printf("%d %d %d\n", v[i].id, v[i].de, v[i].cai);
// cout<< v[i].id<< " "<< v[i].de<< " "<< v[i].cai<< endl;
}
}
int main() {
int n, l, h;
// cin>> n>> l>> h;
scanf("%d %d %d", &n, &l, &h);
vector<Student> v1, v2, v3, v4;
int num= 0;
// input
for (int i= 0; i< n; i++) {
int Id, d, c;
// cin>> Id>> d>> c;
scanf("%d %d %d", &Id, &d, &c);
if (d>= l&& c>= l) {
Student temp(Id, d, c);
if (d>= h&& c>= h) {
v1.push_back(temp);
} else if (d>= h&& c< h) {
v2.push_back(temp);
} else if (d< h&& c< h&& d>= c) {
v3.push_back(temp);
} else {
v4.push_back(temp);
}
num++;
}
}
// sort
if (!v1.empty()) sort(v1.begin(), v1.end(), cmp);
if (!v2.empty()) sort(v2.begin(), v2.end(), cmp);
if (!v3.empty()) sort(v3.begin(), v3.end(), cmp);
if (!v4.empty()) sort(v4.begin(), v4.end(), cmp);
// print
// cout<< num<< endl;
printf("%d\n", num);
myPrint(v1);
myPrint(v2);
myPrint(v3);
myPrint(v4);
}