USACO Score Inflation

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.
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值