天天看點

hdu 1280 前m大的數 (hash)

點選打開連結

典型的hash: 用數組下标表示兩兩相加所得到的和,開辟一個滿足題意的大小的數組 sum,

hdu 1280 前m大的數 (hash)

這樣下标由大到小輸出m個就可以 */

#include <stdio.h>
#include <string.h>
int main ()
{
    int a[3001];
    int sum[10010];
    int n, m;
	int i,j;
    while ( scanf ("%d %d", &n, &m) != EOF )
    {
		memset ( a, 0, sizeof (a) );
		memset ( sum, 0, sizeof (sum) );
		for ( i = 0; i < n; i ++ )
		{
			scanf ("%d", &a[i]);
		}
		
		int temp;
		for ( i = 0; i < n; i ++ )
		{
			for ( j = i + 1; j < n; j++ )
			{
				temp = a[i] + a[j];
				sum[temp] ++;
			}
		}
		
		int count = 0;      //輸出前 m  個數
		for ( i = 10001; i >= 0 ; i -- )
		{
			if ( sum[i] )
			{
				for (j = 0; j < sum[i]; j ++)
				{
					count ++;
					count == 1 ? printf ("%d", i) : printf (" %d", i);
					if ( count == m )
						break;
				}
			}
			if ( count == m )
				break;
		}
		
		printf ("\n");
    }
	return 0;
}