PAT 1055. The World's Richest (25) 年龄排序问题(O(n)排序)

#include<cmath>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<stack>
#include<vector>
#include<queue>
#include<string>
#include<map>
using namespace std;


//100min
//耗时于思路、重制代码,大部分时间用于提高算法效率
/*************************
**题意:给出一堆富豪(10^6个)的年龄和资产,要查询某年龄区间内的m个富豪,最多查1000次
**要求先按资产从大到小,再按年龄从小到大,再按字母序
*************************/


/************************
**求解:如果按照要求排序,显然为nlogn,不会超时
**但是如果要查询1000次,做遍历查询显然超时
**故结合题目特点:年龄最多0-200,查询年龄为区间,只需要查出m个排在前面的富豪。
**故把各富豪按年龄分到各自年龄vector中
**对各年龄数组进行排序,先按资产,后按字母序
**每个年龄数组维持一个当前最大值
**要查询时,从agemin数组查到agemax数组,从各数组的最大值中 找到最大值
**这样查询1k次,最多需要1k*200=2*10^5次。
************************/


/***
笔记:
★sort、cmp的用法
★不确定数组的个数时,尽量用vector而不是预设数组大小。
★先分析时间复杂度,再开始写代码
***/


#define M 100005


struct People
{
string name;
int age;
int weigh;
};


//struct People people[205][M];
vector<struct People> people[205];


bool cmp(struct People a,struct People b) //  a<b是递增,a>b是递减
{
    if(a.weigh > b.weigh)
       return true;
else if(a.weigh==b.weigh)
{
if(a.name < b.name)
return true;
else return false;
}
    else return false;
};     //没有cmp则默认为递增


int an[205];


int main()
{
int n,k,i,a,w;
string s;
memset(an,0,sizeof(an));
scanf("%d%d",&n,&k);
struct People p;
for(i=0;i<n;i++)
{
cin>>s>>a>>w;
p.name=s;
p.age=a;
p.weigh=w;
people[a].push_back(p);
}


for(i=1;i<205;i++)
sort(people[i].begin(),people[i].end(),cmp);

int j,m,amin,amax;
vector<People> ans;
int wmax;
struct People maxp;
int nown[205];
int select;
for(i=0;i<k;i++)
{
scanf("%d%d%d",&m,&amin,&amax);


ans.clear();
memset(nown,0,sizeof(nown));


while(m>0)
{
wmax=-2000000;
for(j=amin;j<=amax;j++)
{
//printf("j=%d, nown=%d,  an=%d \n",j,nown[j],an[j]);
//某年龄的第nown个与最大值做判断,挑出最大的。
if(nown[j] < people[j].size() && people[j][ nown[j] ].weigh > wmax)
{
wmax = people[j][ nown[j] ].weigh;
maxp = people[j][ nown[j] ]; 
select = j;
}
}

if(wmax == -2000000)
break;
ans.push_back(maxp);
nown[select]++;
m--;
}




printf("Case #%d:\n",i+1);
if(ans.size()==0)
cout<<"None"<<endl;


for(j=0;j<ans.size();j++)
{
cout<<ans[j].name<<" "<<ans[j].age<<" "<<ans[j].weigh<<endl;
}


}


return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值