前m大的数
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 17191 Accepted Submission(s): 5866
Problem Description
还记得Gardon给小希布置的那个作业么?(上次比赛的1005)其实小希已经找回了原来的那张数表,现在她想确认一下她的答案是否正确,但是整个的答案是很庞大的表,小希只想让你把答案中最大的M个数告诉她就可以了。
给定一个包含N(N<=3000)个正整数的序列,每个数不超过5000,对它们两两相加得到的N*(N-1)/2个和,求出其中前M大的数(M<=1000)并按从大到小的顺序排列。
给定一个包含N(N<=3000)个正整数的序列,每个数不超过5000,对它们两两相加得到的N*(N-1)/2个和,求出其中前M大的数(M<=1000)并按从大到小的顺序排列。
Input
输入可能包含多组数据,其中每组数据包括两行:
第一行两个数N和M,
第二行N个数,表示该序列。
第一行两个数N和M,
第二行N个数,表示该序列。
Output
对于输入的每组数据,输出M个数,表示结果。输出应当按照从大到小的顺序排列。
Sample Input
4 4 1 2 3 4 4 5 5 3 6 4
Sample Output
7 6 5 5 11 10 9 9 8
题意很明显就不赘述了~
因为最多3000个数,和的计算大概有4500000,所以直接开数组或者队列什么存肯定不行,因此来考虑根据数字的大小来判断它是否要塞进我们的结构里;
用优先队列存储,将大数放队尾,小数放队首,当队内增加到m个元素之后,将每一个即将进队的元素与队首元素进行比较,大则入队,小则舍弃;
这时候我们队列是从小到大排列的,输出时要颠倒一下,我直接开了个栈把元素放进去再弹出来了;
最后清空栈;
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
const int N=3005;
int a[N];
struct cmp{
bool operator()(int x,int y){
return x>y;
}
};
stack <int> s;
priority_queue<int,vector<int>,cmp> q;
int main(){
int n,m;
while(~scanf("%d %d",&n,&m)){
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
sort(a+1,a+n+1);
int cnt=0,sum=0;
for(int i=n;i>=1;i--){
for(int j=i-1;j>=1;j--){
cnt++;
sum=a[i]+a[j];
if(cnt<=m){
q.push(sum);
}
else{
if(sum>=q.top()){
q.pop();
q.push(sum);
}
}
}
}
for(int i=1;i<=m;i++){
s.push(q.top());
q.pop();
}
for(int i=1;i<m;i++){
printf("%d ",s.top());
s.pop();
}
printf("%d\n",s.top());
while(s.empty()) s.pop();
}
}
优先队列好好用啊(痴汉脸