题目
1062 Talent and Virtue[https://pintia.cn/problem-sets/994805342720868352/problems/994805410555346944]
我的初始思路
数据结构:
我的思路就是完全按照题目展开的思路,先存起来,然后设置一个Testee的指针数组,存放不同类的Testee的指针,然后对这个指针数组进行排序操作。
typedef struct {
char id[9];
int talent;
int virtue;
int total;
}Testee;
优质解法思路
思路
看到了分组排序的本质也是排序,所以只要把类别作为最高的排序准则,就可以省去人为分组的复杂操作了。(就是这么牛皮)
新知识点
按类别排序可以分组
改进之后我的代码
本想着对于指向testee结构体数组的每个元素的indexes数组排序,但是不能这么做,sort函数只能对结构体排序,即要传给cmp的参数也必须是结构体不能是结构体指针(本想着能减少运行时间)。
#include <stdio.h>
#include <algorithm>
#include <cstring> // 用strcmp函数必须要导入
using namespace std;
const int MAX_NUM = 1e5 + 5;
const int TYPE_NUM = 5;
struct Testee{
char id[10];
int talent;
int virtue;
int total;
int type;
}testee[MAX_NUM];
bool cmp(Testee p, Testee q);
int main()
{
int N = 0; // total num
int M = 0; // both above L
int L = 0;
int H = 0;
int i = 0;
scanf("%d%d%d", &N, &L, &H);
i = 0;
while (i < N) {
scanf("%s %d %d", testee[i].id, &testee[i].virtue, &testee[i].talent);
testee[i].total = testee[i].virtue + testee[i].talent;
if (testee[i].talent < L || testee[i].virtue < L) {
testee[i].type = 5;
}
else { // 虽然确实可以把分类单写一个函数,但是这样直接判断就可以省去调用函数栈的时间,在算法题目中最好这样写
M++;
if (testee[i].talent >= H && testee[i].virtue >= H) {
testee[i].type = 1;
}
else if (testee[i].virtue >= H) {
testee[i].type = 2;
}
else if (testee[i].virtue >= testee[i].talent) {
testee[i].type = 3;
}
else {
testee[i].type = 4;
}
}
i++;
}
sort(testee, testee + N, cmp); // 要对整体进行排序,排完之后就自然前M个变成了符合条件可输出的数据
printf("%d\n", M);
for(i = 0; i < M; i++) {
printf("%s %d %d\n", testee[i].id, testee[i].virtue, testee[i].talent);
}
}
bool cmp(Testee p, Testee q) {
if (p.type != q.type) {
return p.type < q.type;
}
else if (p.total != q.total) {
return p.total > q.total;
}
else if (p.virtue != q.virtue) {
return p.virtue > q.virtue;
}
else {
return strcmp(p.id, q.id) < 0;
}
}
完成度
one kill- double kill
- triple kill