解法一:排序

按照题目要求排序,然后对于每个查询,遍历数组输出年龄满足要求的人。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class People {
  4. public:
  5. string name;
  6. int age;
  7. int worth;
  8. };
  9. bool cmp(People &o1, People &o2) {
  10. if (o1.worth == o2.worth) {
  11. if (o1.age == o2.age) {
  12. return o1.name < o2.name;
  13. } else {
  14. return o1.age < o2.age;
  15. }
  16. } else {
  17. return o1.worth > o2.worth;
  18. }
  19. }
  20. int main() {
  21. ios::sync_with_stdio(false);
  22. cin.tie(0);
  23. int N, K;
  24. cin >> N >> K;
  25. People peoples[N];
  26. for (int i = 0; i < N; ++i) {
  27. cin >> peoples[i].name >> peoples[i].age >> peoples[i].worth;
  28. }
  29. sort(peoples, peoples + N, cmp);
  30. int M, AMin, AMax;
  31. for (int index = 1; index <= K; ++index) {
  32. cin >> M >> AMin >> AMax;
  33. int cnt = 0;
  34. cout << "Case #" << index << ":\n";
  35. for (auto &people:peoples) {
  36. if (cnt >= M) {
  37. break;
  38. }
  39. if (people.age >= AMin && people.age <= AMax) {
  40. cout << people.name << " " << people.age << " " << people.worth << "\n";
  41. ++cnt;
  42. }
  43. }
  44. if (cnt == 0) {
  45. cout << "None\n";
  46. }
  47. }
  48. }