这一题是比较普通的排序题,然而我在第一次做的时候,发现出现超时的情况。于是我又重新审查了一遍题目,发现了一条比较关键信息,就是输出的数据不能超过100条,这也是整道题的突破点。
算法步骤:
- 建立结构体
- 编写比较函数
- 新建结构体数组来存储并进行排序
- 筛选出每个年龄段前100个人,并将这些数据存储到另一个结构体数组中
- 针对每次query,循环遍历出符合条件的数据
- 处理输出数据为0条的情况
这一题难点在于输入n有10的5次方,而m却只有100,又因为age从0到200,最多只要200*100=20000条数据,所以这间接地提示我们要采取方法筛选冗余数据。
方法:
int validnum = 0;
for (int i = 0; i < n;i++){
if(agenum[people[i].age]<100){
agenum[people[i].age]++;
choosed[validnum++] = people[i];
}
}
代码如下:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
struct person{
char name[10];
int age;
int money;
} people[100005],choosed[100005];
bool cmp(person a,person b){
if(a.money!=b.money){
return a.money > b.money;
}else if(a.age!=b.age){
return a.age < b.age;
}else{
int s = strcmp(a.name, b.name);
return s < 0;
}
}
int main(){
int n, k;
int agenum[205] = {0};
scanf("%d %d", &n, &k);
for (int i = 0; i < n;i++){
scanf("%s %d %d", &people[i].name, &people[i].age, &people[i].money);
}
int agemin, agemax, num;
sort(people, people + n,cmp);
int validnum = 0;
for (int i = 0; i < n;i++){
if(agenum[people[i].age]<100){
agenum[people[i].age]++;
choosed[validnum++] = people[i];
}
}
for (int i = 0; i < k;i++){
scanf("%d %d %d", &num, &agemin, &agemax);
int cnt = 0;
printf("Case #%d:\n", i + 1);
for (int j = 0; j < validnum && cnt<num ;j++){
if(choosed[j].age>=agemin && choosed[j].age<=agemax){
printf("%s %d %d\n", choosed[j].name, choosed[j].age, choosed[j].money);
cnt++;
}
}
if(cnt==0){
printf("None\n");
}
}
}