Watashi's BG (深搜)

Watashi is the couch of ZJU-ICPC Team and he is very kind hearted. In ZJU-ICPC summer training camp, students are divided into several groups and each day one of the groups will design some problems to hold a contest. Today students of Group C are required to design the problems, and they spent the whole night to check to test data which made them very tired. Watashi decides to give some money as a reward to group C so that they can buy the lunch for free.

There are N days in the training schedule, and all students have booked their lunch for N days so we know how much money they will spend in each day. Now the leader of group C needs to decide how to use Watashi's money. Since the money is limited, it may not be possible that they can have free lunch every day. So each day the leader can choose to pay for the whole group's lunch by themselves or use Watashi's money. Of course, the leader wants to spend Watashi's money as much as possible, but he is too busy to write a program to calculate the maximum money he can spend from Watashi's reward. Can you help him?

input

The input contains multiple test cases ( no more than 50 test cases ).
In each test case, first there are two integer, N ( 1 <= N <=30 ) , which is the number of training days, M ( 0 <= M <=10000000 ) , which is the reward money from Watashi.
Then there is a line containing N positive integers with the ith integer indicating the money group C need to pay for the lunch of the ith day. All these integers are no more than 10000000 and integers are seperated by a space.

output

For each test case, output one line with an integer which is the maximum money group C can spend from Watashi's reward

sample input

3 10
8 4 5

sample output

9

有n天,告诉你每天的花费,别人给你一笔资金m,你自己也有一部分资金(可以假设花不完),
每天只能花自己的钱或者花资金m中的钱,不能混着花,问m最多能花多少?

深搜算法可以解决,网上百度题解的时候还有另外的做法,二进制的枚举法,没有花时间去研究,有兴趣的可以自己百度一下。
 当前已使用的资金与所有还未使用的资金相加如果小于等于已得到的最大值,则剪枝。
 这个剪枝加入以后代码的运行速度会大大提高,不加的话会在TLE的边缘。 

#include<iostream>   
#include<cstdio>  
#include<algorithm>  
using namespace std;   
int a[40],b[40];  
int n,m,maxm;  
void dfs(int step,int cnt)
{  
    if(cnt>m)   
	return ;  
    maxm=max(maxm,cnt);  
    if(step<1) 
	return ;  
    if(cnt+b[step]<=maxm)  //当前已使用的资金与所有还未使用的资金相加如果小于等于已得到的最大值,则剪枝。
	return ;    //防TLE剪枝  ,这个不加的话会在超时的边缘 
    dfs(step-1,cnt);  
    dfs(step-1,cnt+a[step]);  
}  
int main(){  
    int i,j;  
    while(scanf("%d%d",&n,&m)!=EOF)  
    {  
        for(i=1;i<=n;i++)  
        scanf("%d",&a[i]);   
        b[0]=0;  
        for(i=1;i<=n;i++)    
		b[i]=b[i-1]+a[i];  
        maxm=0;  
        dfs(n,0);  
        printf("%d\n",maxm);  
    }  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值