TOJ 2811 Bessie's Weight Problem DP

2811: Bessie's Weight Problem

描述

Bessie, like so many of her sisters, has put on a few too many pounds enjoying the delectable grass from Farmer John's pastures. FJ has put her on a strict diet of no more than H (5 <= H <= 45,000) kilograms of hay per day.

Bessie can eat only complete bales of hay; once she starts she can't stop. She has a complete list of the N (1 <= N <= 500) haybales available to her for this evening's dinner and, of course, wants to maximize the total hay she consumes. She can eat each supplied bale only once, naturally (though duplicate weight valuess might appear in the input list; each of them can be eaten one time).

Given the list of haybale weights W_i (1 <= W_i <= H), determine the maximum amount of hay Bessie can consume without exceeding her limit of H kilograms (remember: once she starts on a haybale, she eats it all).

输入

* Line 1: Two space-separated integers: H and N

* Lines 2..N+1: Line i+1 describes the weight of haybale i with a single integer: W_i

输出

* Line 1: A single integer that is the number of kilograms of hay that Bessie can consume without going over her limit.

样例输入

56 4
15
19
20
21

样例输出

56

提示

INPUT DETAILS: 
Four haybales of weight 15, 19, 20, and 21. Bessie can eat as many as she wishes without exceeding the limit of 56 altogether.

OUTPUT DETAILS:
Bessie can eat three bales (15, 20, and 21) and run right up to the limit
of 56 kg.

 

因为价值和重量是一样的,所以用一位数组就可以存了,下标代表重量。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int dp[50000];
int main()
{
	int n,m,i,j,a[505],s;
    scanf("%d%d",&m,&n);
    for(i=1;i<=n;i++)
    scanf("%d",&a[i]);
    memset(dp,0,sizeof dp);
    for(i=1;i<=n;i++)
    {
    	for(j=m;j>=a[i];j--)
    	{
	    	s=dp[j-a[i]]+a[i];
	    	if(s<=m&&s>dp[j])
	    	dp[j]=s;
	    	//printf("i:%d j:%d dp[j]:%d\n",i,j,dp[j]);
	    }
    }
    printf("%d\n",dp[m]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值