#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; struct People { string name; int age; int net_worth; }; vector<People> people; bool cmp(const People &a, const People &b) { if (a.net_worth != b.net_worth) return a.net_worth > b.net_worth; else { if (a.age != b.age) return a.age < b.age; else return a.name < b.name; } } int main() { int n, k; cin >> n >> k; people.resize(n); for (int i = 0; i < n; i++) { cin >> people[i].name; scanf("%d %d", &people[i].age, &people[i].net_worth); } sort(people.begin(), people.end(), cmp); int counts[201] = { 0 }; int remain[100005]; int remain_cnt = 0; for (int i = 0; i < n; i++) { if (++counts[people[i].age] < 101) remain[remain_cnt++] = i; } int m, small, big; for (int i = 0; i < k; i++) { int cnt = 0; cin >> m >> small >> big; cout << "Case #" << i + 1 << ":" << endl; int age; for (int j = 0; j < remain_cnt && cnt < m; j++) { age = people[remain[j]].age; if (age >= small && age <= big) { cnt++; printf("%s %d %d\n", people[remain[j]].name.c_str(), people[remain[j]].age, people[remain[j]].net_worth); } } if (cnt == 0) cout << "None" << endl; } return 0; }
这个题目思路很简单,但是会有超时的问题。解决方法是在排序好之后,遍历一遍,如果某个年龄出现的次数超过100之后,下次碰到这个年龄就跳过。