1. 程式人生 > >HIT1485 A Good Helper(0-1背包)

HIT1485 A Good Helper(0-1背包)

accepted num test case eof 做的 nbsp 心態 ive tor

終於補完第二次期末考了……果然考場上心態不好導致好多會做的題都沒時間寫

題目鏈接:

  http://acm.hit.edu.cn/hoj/problem/view?id=1485

題目描述:

A Good Helper

Submitted : 713, Accepted : 320

Abraham and Calford are Moving their things from dormitory A11 to A9,and they have their own carry limit,they can‘t carry things which is beyond their limit and they will not carry one bag together. They want things to be carried in one time,when they can‘t deal with so many things, they will hire a good helper to help them, who can only carry one bag of things, regardless of the weight of it. Your task is to tell whether they can carry their bags in one time,or not.

Input
There are multiple test cases.
First line of each test case contains two nonnegative numbers, A and C, (0 < A,C <=1000) representing the limit of Abraham and Calford,then the second line contains an integer N ( 0 < N <= 200 ) ,representing the number of bags,followed by N positive integers,each of them is not more than 100.

Output
For each test case
Output "Yes" if they can carry the bags without the help of the helper in one time.
Output "Need a helper" if they can only carry the bags with the help of the helper in one time.
Output "No" if they can‘t carry the bags in one time.

Sample Input

7 7
3 5 5 5
7 7
3 5 2 5
7 7
3 7 8 7
7 7
3 7 8 9

Sample Output

Need a helper
Yes
Need a helper
No

題目大意:

  兩個人搬東西,給你各自能搬的最大重量,這時如果還剩一個東西搬不動,可以請一個幫手,幫手只能搬一個東西但不限重量

  問能否一次辦完並是否需要幫手

思路:

  先貪心取得最大重量得物品給幫手搬,求出剩下的和

  以A的容量做0-1背包,看剩下的容量C能否搬動

  如果C的容量減去剩余的容量還能把幫手手中的物品搬動,則不需要幫手

代碼:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 const int N = 210;
 8 
 9 int num[N], dp[5 * N] = { 0 };
10 
11 int main() {
12     int A, C, n, sum, best, res;
13     while (cin >> A >> C) {
14         cin >> n;
15         sum = best = 0;
16         for (int i = 1; i <= n; ++i) {
17             scanf("%d", &num[i]);
18             sum += num[i];
19             if (num[i] > best) { best = num[i]; res = i; }
20         }
21         sum -= best;    //除去最大後的剩余和
22         memset(dp, 0, sizeof(dp));
23         for (int i = 1; i <= n; ++i) if (i != res)    //0-1背包
24             for (int j = A; j >= num[i]; --j)
25                 dp[j] = max(dp[j], dp[j - num[i]] + num[i]);
26         if (sum - dp[A] > C)printf("No\n");    //有幫手C也拿不動
27         else if (sum - dp[A] + best <= C)printf("Yes\n");    //C還可以再拿幫手拿的那個東西
28         else printf("Need a helper\n");    //C拿不動最大的東西,但剩下的可以和A分掉
29     }
30 }

HIT1485 A Good Helper(0-1背包)