用 hash 做
Accepted |
1280 |
0MS |
292K |
1236B |
G++ |
//典型的hash: 用数组下标表示两两相加所得到的和,开辟一个满足题意的大小的数组 sum,
//这样下标由大到小输出m个就可以
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int a[3001];
int sum[10001];
int n, m;
while ( scanf ("%d %d", &n, &m) != EOF )
{
memset ( a, 0, sizeof (a) );
memset ( sum, 0, sizeof (sum) );
for ( int i = 0; i < n; i ++ )
{
scanf ("%d", &a[i]);
}
int temp;
for ( int i = 0; i < n; i ++ )
{
for ( int j = i + 1; j < n; j++ )
{
temp = a[i] + a[j];
sum[temp] ++;
}
}
int count = 0; //输出前 m 个数
for ( int i = 10001; i >= 0 ; i -- )
{
if ( sum[i] )
{
for (int 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");
}
// system ("pause");
return 0;
}
所以改用sort排序后再输出
Accepted |
1280 |
843MS |
17888K |
1304B |
G++ |
//典型的hash: 用数组下标表示两两相加所得到的和,开辟一个满足题意的大小的数组 sum,
//这样下标由大到小输出m个就可以
#include <iostream>
#include <string>
using namespace std;
int sum[4500000]; //开全局数组才能过
bool cmp ( const int &a, const int &b )
{
return a > b;
}
int main ()
{
int a[3001];
int n, m;
while ( scanf ("%d %d", &n, &m) != EOF )
{
memset ( a, 0, sizeof (a) );
memset ( sum, 0, sizeof (sum) );
//输入处理
for ( int i = 0; i < n; i ++ )
{
scanf ("%d", &a[i]);
}
//两数求和
//int k = n * ( n - 1 ) / 2;
int temp = 0;
for ( int i = 0; i < n; i ++ )
{
for ( int j = i + 1; j < n; j ++ )
{
sum[temp ++] = a[i] + a[j];
}
}
sort ( sum, sum + temp, cmp );
int count = 0;
for ( int i = 0; i< temp; i ++ )
{
count ++;
count == 1 ? printf ("%d", sum[i]): printf (" %d",sum[i]);
if ( count == m )
break;
}
printf ("\n");
}
// system ("pause");
return 0;
}
posted on 2010-08-28 16:43
雪黛依梦 阅读(425)
评论(0) 编辑 收藏 引用 所属分类:
哈希法 、
排序题