列表

详情


NC24851. [USACO 2009 Oct G]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 Wi (1 <= Wi <= 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).
POINTS: 250

输入描述

* 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: Wi

输出描述

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

示例1

输入:

56 4
15
19
20
21

输出:

56

说明:

Four haybales of weight 15, 19, 20, and 21. Bessie can eat as many as she wishes without exceeding the limit of 56 altogether.
Bessie can eat three bales (15, 20, and 21) and run right up to the limit of 56 kg.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 19ms, 内存消耗: 724K, 提交时间: 2019-08-30 14:01:10

#include<iostream>
#include<algorithm>
using namespace std;

int h, n, a, dp[45005];

int main() {
	cin >> h >> n;
	for(int i = 0; i < n; i++) {
		cin >> a;
		for(int j = a; j <= h; j++) dp[j] = max(dp[j], dp[j-a]+a);
	}
	cout << dp[h] << endl;
	return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 23ms, 内存消耗: 508K, 提交时间: 2019-08-30 12:34:01

#include<bits/stdc++.h>
using namespace std;
int a[510],dp[45010];
int main(){
	int n,m;
	cin>>m>>n;
	for(int i=1;i<=n;i++)
	cin>>a[i];
	for(int i=1;i<=n;i++)
	for(int j=m;j>=a[i];j--)
	dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
	cout<<dp[m]<<"\n";
	return 0;
}

Pascal(fpc 3.0.2) 解法, 执行用时: 22ms, 内存消耗: 376K, 提交时间: 2019-08-30 08:15:17

var m,n,i,j:longint;
    w,f:array[1..50000]of longint;
begin
  readln(m,n);
  for i:=1 to n do
    readln(w[i]);
  for i:=1 to n do
    for j:=m downto w[i] do
      if f[j]<f[j-w[i]]+w[i] then f[j]:=f[j-w[i]]+w[i];
  write(f[m]);
end.

pypy3(pypy3.6.1) 解法, 执行用时: 132ms, 内存消耗: 20336K, 提交时间: 2021-05-03 21:09:16

N=[]
H=[0]*46000
h,n=map(int,input().split())
for i in range(n):
    N.append(int(input()))
for i in range(n):
    for j in range(h,N[i]-1,-1):
        H[j]=max(H[j],H[j-N[i]]+N[i])
print(H[h])    

上一题