HDOJ 1280 前m大的数

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

题解

快排好像也可以过,这里贴出hash的方法,空间换时间的思想节省不少时间

CODE

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <time.h>
using namespace std;
int main()
{
    int n,m;
    int b[3010];
    while(cin >> n >> m)
    {
        int maxn=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&b[i]);
            maxn=max(maxn,b[i]);
        }

        int a[2*maxn+1],t=0;
        memset(a,0,sizeof(a));
        for(int i=0; i<n; i++)
            for(int j=i+1; j<n; j++)
                a[b[i]+b[j]]++;
        int count=0;
        bool c=0;
        for(int i=maxn+maxn; count!=m; i--)
        {
            if(a[i]!=0)
            {
                if(c)
                {
                    while(a[i]--)
                    {
                        cout << ' ' << i ;
                        count++;
                        if(count == m)
                            break;
                    }
                }
                else
                {
                    while(a[i]--)
                    {
                        if(c)
                            cout <<  ' ' << i;
                        else
                        {
                            cout << i;
                            c=1;
                        }

                        count++;
                        if(count == m)
                            break;
                    }
                }


            }

        }
        cout << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/AC__GO/article/details/81178193