dp 01背包 模板
#include <bits/stdc++.h> using namespace std; const int N = 10000; int n; unsigned long long res=0; struct bag{ int value; int weight; }bag[N]; int M,dp[N][N]; int main(){ cin>>M>>n; for (int i = 1; i <= n; i++) { cin>>bag[i].weight>>bag[i].value; } for (int i = 1; i <= n; i++) { for (int j = 0; j <= M; j++) { if(bag[i].weight<=j){ dp[i][j]=max(dp[i-1][j],dp[i-1][j-bag[i].weight]+bag[i].value); }else dp[i][j]=dp[i-1][j]; } } cout<<dp[n][M]; return 0; }
完全背包:
#include <bits/stdc++.h> using namespace std; const int N = 10000; int n; unsigned long long res=0; struct bag{ int value; int weight; int amount; }bag[N]; int M,dp[N]; int main(){ ios::sync_with_stdio(false); cin>>M>>n; for (int i = 1; i <= n; i++) { cin>>bag[i].weight>>bag[i].value>>bag[i].amount; } for (int i = 1; i <= n; i++) { for (int j = bag[i].weight; j <= M; j++) { if(bag[i].weight<=j){ dp[j]=max(dp[j],dp[j-bag[i].weight]+bag[i].value); } } } cout<<"max="<<dp[M]<<endl; return 0; }
分组背包:
#include<bits/stdc++.h> using namespace std; const int N = 110; int dp[N],m,n,s,v[N],w[N]; int main(){ cin>>n>>m; for(int i=0;i<n;i++){ cin>>s; for(int j=0;j<s;j++) cin>>v[j]>>w[j]; for(int j=m;j>=0;j--) for(int k=0;k<s;k++) if(v[k]<=j) dp[j]=max(dp[j],dp[j-v[k]]+w[k]); } cout<<dp[m]<<endl; return 0; }
本文在博客园发布,作者:limited_Infinite,转载请注明原文链接:https://www.cnblogs.com/limitedInfinite/p/14635059.html