Scales(dfs背包+剪枝)

来源:互联网 发布:花形透 知乎 编辑:程序博客网 时间:2024/06/08 15:47

Scales
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 3148 Accepted: 851

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.

Output

Line 1: A single integer that is the largest mass that can be accurately and safely measured.

Sample Input

3 1511020

Sample Output

11

Hint

Explanation of the sample: 

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. 

The 1 and 10 weights are used to measure 11. Any greater weight that can be formed from the weights will break the balance.

Source

USACO 2005 December Silver

题意:给你n个砝码,让你从中挑出一些砝码(每个砝码只得用一次),使得重量之和最大,但不能超过C,问最大重量是多少?

思路:从后往前进行搜索,判断,注意用前缀求和函数来进行剪枝。

代码:

    #include<iostream>      #include<cstdio>      #include<cstdlib>      #include<cmath>      #include<cstring>      #include<algorithm>      using namespace std;      typedef long long ll;      ll a[1000],b[1000],n,c,ans;      void dfs(int x,ll y){          if(y>ans)ans=y;  //找最大值        if(x<1)return;    //结束条件        for(int i=x;i>=1;i--){              if(y+a[i]<=c && y+b[i]>ans) //注意这是关键的剪枝                  dfs(i-1,y+a[i]);          }      }      int main(){          ios::sync_with_stdio(false);        int i,j,k,m;          while(cin>>n>>c){              b[1]=0;              ans=0;              for(i=1;i<=n;i++){                  cin>>a[i];                  b[i]=b[i-1]+a[i];              }              dfs(n,0);              cout<<ans<<endl;          }          return 0;      }  


原创粉丝点击