题目大意:给出N个人的姓名、年龄和资产信息,要求输出在指定年龄区间内最富有的M个人的信息。
按照资产排序后,直接暴力遍历所有人的信息,符合年龄要求的输出,并维护已经输出的数量<=M即可。不过这样测试点2耗时会比较长,题目似乎更改了时间限制,按照以前的200ms的时间限制需要换一种思路,即一开始就要将每个年龄的前M个人单独存放到数组里,查询的时候从这个数组里查询。不过既然放宽了时间限制,暴力做法也能过。
AC代码:
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
struct person
{
char name[10];
int age;
int worth;
bool operator <(const person &other)
{
if(this->worth != other.worth) return this->worth > other.worth;
else if(this->age != other.age) return this->age < other.age;
else return strcmp(this->name, other.name) < 0;
}
};
int main()
{
int N, K;
scanf("%d%d", &N, &K);
vector<person> v(N);
for (int i = 0; i < N; ++i)
scanf("%s%d%d", v[i].name, &v[i].age, &v[i].worth);
sort(v.begin(), v.end());
for (int query = 1; query <= K; ++query)
{
int M, Amin, Amax;
scanf("%d%d%d", &M, &Amin, &Amax);
printf("Case #%d:\n", query);
int printNum = 0;
for (int i = 0; i < N && printNum < M; ++i)
{
if(v[i].age >= Amin && v[i].age <= Amax)
{
printf("%s %d %d\n", v[i].name, v[i].age, v[i].worth);
printNum++;
}
}
if(printNum == 0) printf("None\n");
}
return 0;
}