PAT Grade A 1055 The World's Richest (25 points)|C++ implementation

1. Title description

原题链接
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:

Insert picture description here

​​Output Specification:

Insert picture description here

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

Two, problem-solving ideas

A simple structure sorting problem, define a structure to represent people, including name, age and wealth, and then use the sort function to sort, according to the age range given by the title, we can output.

Three, AC code

#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;
}

Guess you like

Origin blog.csdn.net/weixin_42393947/article/details/108614703