01背包(hdoj 饭卡问题,5块随便买,问最大价值):
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,V,w[1005],dp[1005];
while(cin>>n&&n){
memset(dp,0,sizeof(dp));
for(int i = 1;i <= n;i++)
cin>>w[i];
cin>>V;
sort(w+1,w+1+n);
if(V < 5) cout<<V<<endl;
else{
for(int i = 1;i < n;i++){
for(int j = V-5;j >= w[i];j--){
dp[j] = max(dp[j],dp[j-w[i]]+w[i]);
}
}
cout<<V-dp[V-5]-w[n]<<endl;
}
}
return 0;
}
完全背包(hdoj 1114,完全背包,问能不能装满f-e的重量):
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+10;
int main(){
int t,e,f,n;
scanf("%d",&t);
while(t--){
scanf("%d%d",&e,&f);
scanf("%d",&n);
int dp[maxn];
dp[0] = 0;
for(int i = 1;i < maxn;i++)
dp[i] = INF;
for(int i = 0;i < n;i++){
int weight,value;
scanf("%d%d",&value,&weight);
for(int j = weight;j <= f-e;j++)
dp[j] = min(dp[j],dp[j-weight]+value);
}
if(dp[f-e] == INF) printf("This is impossible.\n");
else printf("The minimum amount of money in the piggy-bank is %d.\n",dp[f-e]);
}
return 0;
}
多重背包(hdoj 2191)
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
int t,nValue,nKind,value[105],weight[105],bag[105],dp[105];
int main(){
scanf("%d",&t);
while(t--){
memset(dp,0,sizeof(dp));
scanf("%d%d",&nValue,&nKind);
for(int i = 0;i < nKind;i++){
scanf("%d%d%d",&value[i],&weight[i],&bag[i]);
for(int j = 0;j < bag[i];j++){
for(int k = nValue;k >= value[i];k--){
dp[k] = max(dp[k],dp[k-value[i]]+weight[i]);
}
}
}
printf("%d\n",dp[nValue]);
}
return 0;
}