标签:
可做hdu2602:http://acm.hdu.edu.cn/showproblem.php?pid=2602
代码1:
#include <fstream> #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> using namespace std; #define N 1007 int c[N],w[N],dp[N][N]; int main(){ //freopen("D:\\input.in","r",stdin); int t,i,n,V,v; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&V); for(i=1;i<=n;i++) scanf("%d",&c[i]); for(i=1;i<=n;i++) scanf("%d",&w[i]); for(i=0;i<=V;i++) dp[0][i]=0; for(i=1;i<=n;i++){ for(v=0;v<=V;v++){ if(v>=w[i]) dp[i][v] = max(dp[i-1][v],dp[i-1][v-w[i]]+c[i]); else dp[i][v] = dp[i-1][v]; } } printf("%d\n",dp[n][V]); } return 0; }
代码2(空间优化):
#include <iostream> #include <cstdio> #include <cstring> using namespace std; #define N 1007 int c[N],w[N],dp[N]; int main(){ int t,i,n,V,v; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&V); for(i=1;i<=n;i++) scanf("%d",&c[i]); for(i=1;i<=n;i++) scanf("%d",&w[i]); memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++){ for(v=V;v>=w[i];v--) dp[v] = max(dp[v],dp[v-w[i]]+c[i]); } printf("%d\n",dp[V]); } return 0; }
恰好装满版本:
#include <fstream> #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> using namespace std; #define N 1007 #define INF 0x7fffffff int c[N],w[N],dp[N]; int main(){ int t,i,n,V,v; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&V); for(i=1;i<=n;i++) scanf("%d",&c[i]); for(i=1;i<=n;i++) scanf("%d",&w[i]); dp[0]=0; for(i=1;i<=V;i++) dp[i]=-INF; for(i=1;i<=n;i++) for(v=V;v>=w[i];v--) dp[v] = max(dp[v],dp[v-w[i]]+c[i]); n=dp[V]; if(n>0) printf("%d\n",n); else printf("无法恰好装满!\n"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/jiu0821/p/4518652.html