目录
题目描述
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Problem Description
还记得Gardon给小希布置的那个作业么?(上次比赛的1005)其实小希已经找回了原来的那张数表,现在她想确认一下她的答案是否正确,但是整个的答案是很庞大的表,小希只想让你把答案中最大的M个数告诉她就可以了。
给定一个包含N(N<=3000)个正整数的序列,每个数不超过5000,对它们两两相加得到的N*(N-1)/2个和,求出其中前M大的数(M<=1000)并按从大到小的顺序排列。
Input
输入可能包含多组数据,其中每组数据包括两行:
第一行两个数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
题意分析
题意:N个数两两相加,然后输出前M个数字。模拟相加sort一遍能过。注意数组开的过大会超时
推荐使用散列(哈希表)去解此题
AC代码
#include <iostream>
#include <algorithm>
#define MAXN 500005
using namespace std;
int x[3005];
int y[3000*1500+5];
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int n,m,i,j,p;
while(~scanf("%d%d",&n,&m))
{
p=0;
for(i=0;i<n;i++)
{
cin>>x[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
y[p++]=x[i]+x[j];
}
}
sort(y,y+p,cmp);
for(i=0;i<m;i++)
{
cout<<y[i];
if(i!=m-1)
{
cout<<' ';
}
else
{
cout<<endl;
}
}
}
return 0;
}