您的位置:首页 > 其它

1055.The World's Richest

2015-01-21 19:34 309 查看
【题意】
给出一些人的名字、年龄、财富,求一定年龄范围内、一定人数内的财富榜

【思路】
先按财富、年龄、姓名顺序排个序,然后筛选出年龄符合要求的输出

【注意点】
需要进行剪枝才能过Case 1(目测Case 1的测试数据前面是1串同一年龄但不在要求范围内的人,若不剪枝会超时。其实我用先对年龄排序,再二分法找上下限位置的方法也能过Case 1,但Case 2过不去),跳过的人是排序后同一年龄里排在100名之后的,因为题目中说排行榜最多100个人

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
using namespace std;

typedef struct{
char name[9];
int age;
int net_worth;
}info;

bool cmp(info i1, info i2){
if(i1.net_worth>i2.net_worth){
return 1;
}
else if(i1.net_worth==i2.net_worth && i1.age<i2.age){
return 1;
}
else if(i1.net_worth==i2.net_worth && i1.age==i2.age && strcmp(i1.name,i2.name)<0){
return 1;
}
else{
return 0;
}
}

int main(int argc, char const *argv[])
{
int n,k;
vector<info> infos;
vector<info>::iterator it;
vector<int> filter;
int ageCnt[200];

memset(ageCnt,0,sizeof(ageCnt));

scanf("%d%d", &n, &k);
infos.resize(n);
for(int i=0; i<n; i++){
scanf("%s%d%d", infos[i].name, &infos[i].age, &infos[i].net_worth);
}
sort(infos.begin(),infos.end(),cmp);

int filterNum = 0;
filter.resize(n);
for(int i=0; i<n; i++){
if(++ageCnt[infos[i].age]<=100){
filter[filterNum++] = i;
}
}

for(int i=0; i<k; i++){
int m,amin,amax,cnt;

scanf("%d%d%d", &m, &amin, &amax);
printf("Case #%d:\n", i+1);

cnt = 0;
for(int i=0; i<filterNum && cnt<m; i++){
int index = filter[i];
if(infos[index].age>=amin && infos[index].age<=amax){
printf("%s %d %d\n", infos[index].name, infos[index].age, infos[index].net_worth);
cnt++;
}
}

if(cnt==0){
printf("None\n");
}
}

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: