Hay For Sale

问题 A: Hay For Sale

时间限制: 1 Sec   内存限制: 12 MB
提交: 175   解决: 39
[ 提交][ 状态][ 讨论版]

题目描述

Farmer John suffered a terrible loss when giant Australian cockroaches ate the entirety of his hay inventory, leaving him with nothing to feed the cows. He hitched up his wagon with capacity C (1 <= C <=  50,000) cubic units and sauntered over to Farmer Don's to get some hay before the cows miss a meal. 

Farmer Don had a wide variety of H (1 <= H <= 5,000) hay bales for sale, each with its own volume (1 <= V_i <= C). Bales of hay, you know, are somewhat flexible and can be jammed into the oddest of spaces in a wagon. 

FJ carefully evaluates the volumes so that he can figure out the largest amount of hay he can purchase for his cows. 

Given the volume constraint and a list of bales to buy, what is the greatest volume of hay FJ can purchase? He can't purchase partial bales, of course. Each input line (after the first) lists a single bale FJ can buy. 

输入

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

* Lines 2..H+1: Each line describes the volume of a single bale: V_i 

输出

* Line 1: A single integer which is the greatest volume of hay FJ can purchase given the list of bales for sale and constraints. 

样例输入

7 3
2
6
5

样例输出

7

使用01背包法做:

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
	int num, c;
	cin >> c >> num;
	int *v = new int[num+1];
	for (int i = 1; i <=num; i++)
	{
		cin >> v[i];
	}
	int *dp = new int[c+1];
	memset(dp, 0, (c+1)*sizeof(int));
	
		

	for (int i = 1; i <= num; i++)
	{
		for (int j = c; j >= v[i]; j--)
			dp[j] = max(dp[j], dp[j - v[i]] + v[i]);
		if (dp[c] == c)
			i = num;
	}
	


	cout << dp[c]<<endl;

	delete []v;
	delete []dp;
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值