HDU 1171 Big Event in HDU 多重背包
这题是我第一次写多重背包,1RE,1WA,
#include<stdio.h> #include<string.h> int n,v[55],num[55],dp[250000],sum,all; int max( int a,int b ) { return a > b ? a : b; } int main( ) { while( scanf( "%d",&n ),n > 0 ) { sum = 0; for( int i = 0; i < n; ++i ) scanf( "%d%d",&v[i],&num[i] ),sum += v[i] * num[i]; memset( dp,0,sizeof( dp ) ); all = sum; sum /= 2; for( int i = 0; i < n; ++i ) for( int j = 0 ; j < num[i]; ++j ) for( int k = sum; k >= v[i]; k -= v[i] ) dp[k] = max( dp[k-v[i]]+v[i],dp[k] ); if( dp[sum] > all - dp[sum] ) printf( "%d %d\n",dp[sum],all - dp[sum] ); else printf( "%d %d\n",all - dp[sum],dp[sum] ); } return 0; }
下面这个是标准写法
#include<stdio.h> #include<string.h> int n,v[55],num[55],all,sum,dp[250005]; inline int max( int a,int b ) { return a > b ? a : b; } void zo( int v,int w ) { for( int j = sum; j >= v; --j ) dp[j] = max( dp[j-v] + w,dp[j] ); } void co( int v,int w ) { for( int j = v; j <= sum; ++j ) dp[j] = max( dp[j-v] + w,dp[j] ); } void mu( int v,int w,int c ) { if( v * c > sum ) co( v,w ); else { int k = 1; while( c > k ) { zo( k * v,k * w ); c -= k; k <<= 1; } zo( c * v,c * w ); } } int main( ) { while( scanf( "%d",&n ), n > 0 ) { all = 0; memset( dp,0,sizeof( dp ) ); for( int i = 0; i < n; ++i ) scanf( "%d%d",&v[i],&num[i] ),all += v[i]*num[i]; sum = all / 2; for( int i = 0; i < n; ++i ) mu( v[i],v[i],num[i] ); if( dp[sum] > all - dp[sum] ) printf( "%d %d\n",dp[sum],all - dp[sum] ); else printf( "%d %d\n",all - dp[sum],dp[sum] ); } return 0; }
本人还是新手 ,转载请注明来自Lvsi‘s home