Scales
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 2665 | Accepted: 703 |
Description
Farmer John has a balance for weighing the cows. He also has a set of N (1 <= N <= 1000) weights with known masses (all of which fit in 31 bits) for use on one side of the balance. He places a cow on one side of the balance and then adds weights to the other side until they balance. (FJ cannot put weights on the same side of the balance as the cow, because cows tend to kick weights in his face whenever they can.) The balance has a maximum mass rating and will break if FJ uses more than a certain total mass C (1 <= C < 2^30) on one side.
The weights have the curious property that when lined up from smallest to biggest, each weight (from the third one on) has at least as much mass as the previous two combined.
FJ wants to determine the maximum mass that he can use his weights to measure exactly. Since the total mass must be no larger than C, he might not be able to put all the weights onto the scale.
Write a program that, given a list of weights and the maximum mass the balance can take, will determine the maximum legal mass that he can weigh exactly.
The weights have the curious property that when lined up from smallest to biggest, each weight (from the third one on) has at least as much mass as the previous two combined.
FJ wants to determine the maximum mass that he can use his weights to measure exactly. Since the total mass must be no larger than C, he might not be able to put all the weights onto the scale.
Write a program that, given a list of weights and the maximum mass the balance can take, will determine the maximum legal mass that he can weigh exactly.
Input
Line 1: Two space-separated positive integers, N and C.
Lines 2..N+1: Each line contains a single positive integer that is the mass of one weight. The masses are guaranteed to be in non-decreasing order.
Lines 2..N+1: Each line contains a single positive integer that is the mass of one weight. The masses are guaranteed to be in non-decreasing order.
Output
Line 1: A single integer that is the largest mass that can be accurately and safely measured.
Sample Input
3 15 1 10 20
Sample Output
11 大体题意: 给你n个砝码,让你从中挑出一些砝码(每个砝码只得用一次),使得重量之和最大,但不能超过C,问最大重量是 多少? 思路: C的上限太大,没法01背包dp,那就瞎爆吧= =! 需要加一个剪枝,那就是当前的答案加前面的和 还不如现在已经得到的答案的话,那就不dfs了! 这样dfs去就可以了。 详细见代码:#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 1000 + 10; typedef long long ll; ll a[maxn]; ll sum[maxn]; ll n,c; ll ans; void dfs(int cur,ll ret){ if (ret > ans)ans = ret; if (cur < 1) return ; for (int i = cur; i >= 1; --i){ if (ret + sum[i] <= ans)continue; if (ret + a[i] > c)continue; dfs(i-1,ret+a[i]); } } int main(){ scanf("%I64d %I64d",&n,&c); for (int i = 1; i <= n; ++i){ ans = 0; scanf("%I64d",&a[i]); sum[i] = sum[i-1] + a[i]; } dfs(n,0); printf("%I64d\n",ans); return 0; }