典型的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; }