第一讲:01背包
#include<stdio.h> #include<string.h> int main() { int dp[1000],w[100],c[100]; int i,j,n,v; memset(dp,0,sizeof(dp)); scanf("%d%d",&n,&v); for(i=0;i<n;i++) scanf("%d%d",&w[i],&c[i]); for(i=0;i<n;i++)//第i个物体 for(j=v;j>=c[i];j--)//背包容量V if(dp[j]<dp[j-c[i]]+w[i]) dp[j]=dp[j-c[i]]+w[i]; printf("%d\n",dp[v]); return 0; }第二讲:完全背包
#include<iostream>//c++ #include<cmath>//数学公式 #include<cstdlib>//malloc #include<cstring> #include<string> #include<cstdio>//输入输出 #include<algorithm>//快排 #include<queue>//队列 #include<functional>//优先队列 #include<stack>//栈 #include<vector>//容器 #include<map>//地图 if continue typedef long long ll; const int N=10005; const int inf=0x3f3f3f3f; using namespace std; int dp[N]; int main() { //freopen("C:\\Users\\ch\\Desktop\\1.txt","r",stdin); //freopen("C:\\Users\\lenovo\\Desktop\\2.txt","w",stdout); int i,j,k; int v,n,text; int a,b; cin>>text; while(text--) { memset(dp,inf,sizeof(dp)); dp[0]=0;//初始化数组 cin>>a>>b; v=b-a; cin>>n; for(i=0;i<n;i++) { cin>>a>>b;//价值a->w 体积b->v for(j=b;j<=v;j++) dp[j]=min(dp[j-b]+a,dp[j]); } if(dp[v] == inf) printf("This is impossible.\n"); else printf("The minimum amount of money in the piggy-bank is %d.\n",dp[v]); } return 0; }第六讲:分组背包
#include<iostream>//c++ #include<cmath>//数学公式 #include<cstdlib>//malloc #include<cstring> #include<string> #include<cstdio>//输入输出 #include<algorithm>//快排 #include<queue>//队列 #include<functional>//优先队列 #include<stack>//栈 #include<vector>//容器 #include<map>//地图 if continue typedef long long ll; const int N=105; using namespace std; int dp[N],value[N][N]; int main() { // freopen("C:\\Users\\ch\\Desktop\\1.txt","r",stdin); //freopen("C:\\Users\\lenovo\\Desktop\\2.txt","w",stdout); int i,j,k; int v,n,m; while(cin>>m>>n,n|m) { for(i=0;i<m;i++) for(j=1;j<=n;j++) scanf("%d",&value[i][j]); memset(dp,0,sizeof(dp)); for(int i=0;i<m;i++) for(int j=n;j>=1;j--) for(int k=1;k<=j;k++) dp[j]=max(dp[j],dp[j-k]+value[i][k]); cout<<dp[n]<<endl; } return 0; }
#include<iostream> using namespace std; int f[33333],val[4]={0,1,2,3}; int sum(int a,int b){ return a+b; } int main() { int i,j,n; f[0]=1; for(i=1;i<=3;i++) for(j=i;j<32768;j++) f[j]=sum(f[j],f[j-val[i]]);//可以直接写成f[j]+=f[j-val[i]],这样写只是突出背包的思想; while(scanf("%d",&n)==1) printf("%d\n",f[n]); return 0; }
第九讲:最优方案总数
fill(kry, kry+maxm, INF ); memset(dp, 0, sizeof(dp)); for( int i=1; i<=n; i++ ) { for( int j=m; j>=w[i]; j-- ) { if( dp[j]<dp[j-w[i]]+1) { dp[j] = dp[j-w[i]] + 1; kry[j] = kry[j-w[i]]; } else if( dp[j]==dp[j-w[i]]+1) kry[j] = kry[j] + kry[j-w[i]]; } }
第九讲:输出方案