1 8 2 2 100 4 4 100 2
400
#include<iostream> #include<sstream> #include<algorithm> #include<cstdio> #include<string.h> #include<cctype> #include<string> #include<cmath> #include<vector> #include<stack> #include<queue> #include<map> #include<set> using namespace std; const int INF = 101; struct A { int cost, val,num; }E[INF]; int dp[INF]; int main(){ int t ; cin>>t; while(t--){ memset(dp, 0, sizeof(dp)); int n, m;cin>>n>>m; for(int i = 0; i < m ; i++){ cin>>E[i].cost>>E[i].val>>E[i].num; } for(int i = 0; i< m ; i++){ for(int j = 1; j <= E[i].num; j++){ for(int v = n; v >= E[i].cost; v--){ dp[v] = max(dp[v], dp[v - E[i].cost] + E[i].val); } } } cout<<dp[n]<<endl; } return 0; }第二种是 多重背包转为01背包:
#include<iostream> #include<sstream> #include<algorithm> #include<cstdio> #include<string.h> #include<cctype> #include<string> #include<cmath> #include<vector> #include<stack> #include<queue> #include<map> #include<set> using namespace std; const int INF = 102 * 20; int dp[INF]; struct A { int cost, val; }E[INF]; int main(){ int p, h, c; int t; cin>>t; int n, m; int tot; while(t--){ tot = 0; cin>>n>>m; memset(dp, 0, sizeof(dp)); for(int j = 0; j < m; j++){ cin>>p>>h>>c; for(int i = 0; i < c; i++){ E[tot].cost = p;E[tot++].val = h; } } for(int i = 0; i < tot; i++){ for(int V = n; V >= E[i].cost; V--){ dp[V] = max(dp[V], dp[V - E[i].cost] + E[i].val); } } cout<<dp[n]<<endl; } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
杭电 HDU ACM 2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活(多重背包)
原文地址:http://blog.csdn.net/lsgqjh/article/details/48085349