PAT甲级1055 The World‘s Richest (25分)|C++实现

一、题目描述

原题链接
Forbes magazine publishes every year its list of billionaires based on the annual ranking of the world’s wealthiest people. Now you are supposed to simulate this job, but concentrate only on the people in a certain range of ages. That is, given the net worths of N people, you must find the M richest people in a given range of their ages.

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

Sample Input:

12 4
Zoe_Bill 35 2333
Bob_Volk 24 5888
Anny_Cin 95 999999
Williams 30 -22
Cindy 76 76000
Alice 18 88888
Joe_Mike 32 3222
Michael 5 300000
Rosemary 40 5888
Dobby 24 5888
Billy 24 5888
Nobody 5 0
4 15 45
4 30 35
4 5 95
1 45 50

Sample Output:

Case #1:
Alice 18 88888
Billy 24 5888
Bob_Volk 24 5888
Dobby 24 5888
Case #2:
Joe_Mike 32 3222
Zoe_Bill 35 2333
Williams 30 -22
Case #3:
Anny_Cin 95 999999
Michael 5 300000
Alice 18 88888
Cindy 76 76000
Case #4:
None

二、解题思路

简单的一道结构体排序题,定义一个结构体表示人,包括名字、年龄和财富,然后用sort函数进行排序,根据题目给的年龄范围,我们进行输出即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
struct Person
{
    
    
  int age, worth;
  char name[9];
};
bool cmp(Person a, Person b)
{
    
    
  if(a.worth != b.worth)	return a.worth > b.worth;
  else if(a.age != b.age)	return a.age < b.age;
  else	return strcmp(a.name, b.name) < 0;
}
int main()
{
    
    
  int N, K, M;
  vector<Person> all;
  Person tmp;
  scanf("%d%d", &N, &K);
  for(int i=0; i<N; i++)
  {
    
    
    scanf("%s %d %d", tmp.name, &tmp.age, &tmp.worth);
    all.push_back(tmp);
  }
  sort(all.begin(), all.end(), cmp);
  int maxage, minage, num;
  for(int i=0; i<K; i++)
  {
    
    
    scanf("%d%d%d", &num, &minage, &maxage);
    int cnt = 0;
    printf("Case #%d:\n", i+1);
    for(int j=0; j<all.size(); j++)
    {
    
    
      if(all[j].age >= minage && all[j].age <= maxage)
      {
    
    
        printf("%s %d %d\n", all[j].name, all[j].age, all[j].worth);
        cnt++;
      }
      if(cnt == num)	break;
    }
    if(cnt == 0)
      printf("None\n");
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108614703