寻找大富翁
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4594 Accepted Submission(s): 1871
Problem Description
浙江桐乡乌镇共有n个人,请找出该镇上的前m个大富翁.
Input
输入包含多组测试用例.
每个用例首先包含2个整数n(0<n<=100000)和m(0<m<=10),其中: n为镇上的人数,m为需要找出的大富翁数, 接下来一行输入镇上n个人的财富值.
n和m同时为0时表示输入结束.
Output
请输出乌镇前m个大富翁的财产数,财产多的排前面,如果大富翁不足m个,则全部输出,每组输出占一行.
Sample Input
3 1
2 5 -1
5 3
1 2 3 4 5
0 0
Sample Output
用sort用法
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100010];
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int n,m,i;
while(~scanf("%d %d",&n,&m))
{
if(n==0&&m==0)
return 0;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n,cmp);
if(n>m)
{
for(i=0;i<m-1;i++)
printf("%d ",a[i]);
printf("%d",a[m-1]);
printf("\n");
}
else
{
//sort(a,a+n,cmp);
for(i=0;i<n-1;i++)
printf("%d ",a[i]);
printf("%d",a[n-1]);
printf("\n");
}
}
return 0;
}
优先队列
#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
void abc(int a,int b){
priority_queue<int,vector<int>,less<int> >q;
int c,i;
for(i=0;i<a;++i)
{
scanf("%d",&c);
q.push(c);
}
b=b>a?a:b;
for(i=0;i<b-1;++i)
{
printf("%d ",q.top());
q.pop();
}
printf("%d\n",q.top());
}
int main()
{
int n,m;
while(~scanf("%d %d",&n,&m))
{
if(m==0&&n==0)
return 0;
abc(n,m);
}
return 0;
}