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.
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.
第2到N+1行:每一行仅包含一个正整数,即某个砝码的质量.保证这些砝码的质量是一个不下降序列
Output
* Line 1: A single integer that is the largest mass that can be accurately and safely measured.
一个正整数,表示用所给的砝码能称出的不压坏天平的最大质量.
Sample Input
1
10
20
INPUT DETAILS:
FJ has 3 weights, with masses of 1, 10, and 20 units. He can put at most 15
units on one side of his balance.
Sample Output
HINT
约翰有3个砝码,质量分别为1,10,20个单位.他的天平最多只能承受质量为15个单位的物体.用质量为1和10的两个砝码可以称出质量为11的牛.这3个砝码所能组成的其他的质量不是比11小就是会压坏天平
必须吐槽,传说中所有砝码质量的数值都在31位二进制内,传说中从第三个数字开始,它都大于前面的二个数字之和,那么数据如果要构造得出来,n最多只有30几……剩下的就一阵深搜就好咯,只要深搜不写渣,分分钟0MS……
#include<cstdio> #include<algorithm> #define ll long long using namespace std; ll n,a[40],c,ans=0,q[40]; void dfs(ll p,ll sum){ if (sum+q[p]<=ans) return; if (ans<sum) ans=sum; for (ll i=p;i;i--){ if (sum+a[i]<=c) dfs(i-1,sum+a[i]); } } int main(){ scanf("%lld%lld",&n,&c); for (ll i=1;i<=n;i++){ scanf("%lld",&a[i]); if (a[i]>c) n=i-1;else q[i]=q[i-1]+a[i]; } dfs(n,0); printf("%lld ",ans); }