赤裸裸的0-1背包,用二维数组空间会溢出,优化成一维
Source Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxm = 12880;
const int maxn = 3500;
int c[maxm];
int w[maxn];
int d[maxn];
int M, N;
void dp()
{
memset( c, 0, sizeof( c ) );
for( int i = 1; i <= N; i++ )
{
for( int j = M; j >= 1; j-- )
{
if( j >= w[i] && c[j] < c[j-w[i]] + d[i] )
c[j] = c[j-w[i]] + d[i];
}
}
}
int main()
{
while( ~scanf( "%d%d", &N, &M ) )
{
for( int i = 1; i <= N; i++ )
{
scanf( "%d%d", &w[i], &d[i] );
}
dp();
printf( "%d\n", c[M] );
}
return 0;
}