前言
正文
參考題解
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
/*
題意:從給出的n個人中選擇特定年齡範圍內[Ammin,Amax]的前M個最有錢的人。
排序規則:首先按照資產降序排序,資產相同則按照年齡升序排序,年齡相同,則按照姓名
字典序升序排序,題目保證不會出現資產,年齡,姓名均相同的記錄
考慮到M<=100,故可以將每個年齡段中前100名以內的人都存到
一個新的數組中,然後後續的查詢就在這個數組中進行就可以。
(避免超時,因爲N規模是10^5)
*/
struct person{
char name[20];
int age,worth;
}p[100010],top[100010];
//排序規則
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 age[220];//age[i]表示年齡爲i的人數
int main(){
int n,k,m,Amin,Amax;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++){
scanf("%s%d%d",p[i].name,&p[i].age,&p[i].worth);
}
sort(p,p+n,cmp); //先將所有人進行排序
int count=0;//在某個年齡段中排名前100的人數
for(int i=0;i<n;i++){
if(age[p[i].age]<100){
age[p[i].age]++;
top[count++]=p[i];//將其存入新的數組中
}
}
//k次查詢
for(int i=0;i<k;i++){
scanf("%d%d%d",&m,&Amin,&Amax);
printf("Case #%d:\n",i+1);
int Num=0;//輸出的人數,即Num應不大於m
for(int j=0;j<count&&Num<m;j++){
if(top[j].age>=Amin&&top[j].age<=Amax){
printf("%s %d %d\n",top[j].name,top[j].age,top[j].worth);
Num++;
}
}
if(Num==0){//說明沒有輸出符合條件的人
printf("None\n");
}
}
return 0;
}