1、完全背包问题。。。1Y,《背包九讲》真的很不错。
/*
ID:mrxy564
PROG:inflate
LANG:C++
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int m,n,w[10010],c[10010],dp[10010];
void CompletePack(int w,int c){
for(int j=c;j<=m;j++)
dp[j]=max(dp[j],dp[j-c]+w);
}
int main(){
freopen("inflate.in","r",stdin);
freopen("inflate.out","w",stdout);
scanf("%d%d",&m,&n);
for(int i=0;i<n;i++)
scanf("%d%d",&w[i],&c[i]);
memset(dp,0,sizeof(dp));
for(int i=0;i<n;i++)
CompletePack(w[i],c[i]);
printf("%d\n",dp[m]);
return 0;
}
官方题解:
We use dynamic programming to calculate the best way to use t minutes for all t from 0 to tmax.
When we find out about a new category of problem with points p and length t, we update the best for j minutes by taking the better of what was there already and what we can do by using a p point problem with the best for time j - t.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define MAXCAT 10000 #define MAXTIME 10000 int best[MAXTIME+1]; void main(void) { FILE *fin, *fout; int tmax, ncat; int i, j, m, p, t; fin = fopen("inflate.in", "r"); fout = fopen("inflate.out", "w"); assert(fin != NULL && fout != NULL); fscanf(fin, "%d %d", &tmax, &ncat); for(i=0; i<ncat; i++) { fscanf(fin, "%d %d", &p, &t); for(j=0; j+t <= tmax; j++) if(best[j]+p > best[j+t]) best[j+t] = best[j]+p; } m = 0; for(i=0; i<=tmax; i++) if(m < best[i]) m = best[i]; fprintf(fout, "%d\n", m); exit(0); }
Greg Price writes: After the main `for' loop that does the actual DP work, we don't need to look at the entire array of best point totals to find the highest one. The array is always nondecreasing, so we simply output the last element of the array.
#include <fstream.h> ifstream fin("inflate.in"); ofstream fout("inflate.out"); const short maxm = 10010; long best[maxm], m, n; void main() { short i, j, len, pts; fin >> m >> n; for (j = 0; j <= m; j++) best[j] = 0; for (i = 0; i < n; i++) { fin >> pts >> len; for (j = len; j <= m; j++) if (best[j-len] + pts > best[j]) best[j] = best[j-len] + pts; } fout << best[m] << endl; // This is always the highest total. }