A long stick(深度搜索)

Judge Info


  • Memory Limit: 32768KB
  • Case Time Limit: 10000MS
  • Time Limit: 10000MS
  • Judger: Number Only Judger


Description


There are a lot of problems about sticks. Here is one. I have N\, sticks each with some length of Li(1 \leq Li \leq 1, 000, 000) . I want to use those sticks to make a longer stick with length longer than or equal to B\,. Furthermore, I want the length of the stick as close to B \, as possible.


Task


Now, it is your turn. I will tell you the length of those  N\, sticks, and B\,. Your job is let me know the length of stick which I can have, according the rule above.


Input


The first line of input contains T(1 \leq T \leq 100),the number of test cases. There are two lines for each test case. The first line contains two integer numbers N(1 \leq N \leq 25) and B( 1 \leq B \leq S, S \,is \,the \,sum \,of \,Li ) . The second line contains N \, integer numbers(the length of sticks I have already,  Li \, ).


Output


For each test case, print a line contains the solution.


Sample Input

2
5 14
2 4 3 4 5
5 14
2 4 3 4 5


Sample Output

14
14

用户输入两个数,第一个表示有几根火柴,第二个数是期望长度

接下来是n根火柴的长度,你要取其中几根接起来达到大于等于期望长度,输出最短的那个值

dfs所有组合,一旦发现相等立刻终止搜索,否则就一直求min值


#include<iostream>
using namespace std;
int sum;
bool v[25];
int B;
int stick[25];
int flag=0;
int n;
int minlen;
 
void dfs(int last)
{
	if(flag) return ;
	if(sum!=0)
	{
		if(sum==B)
		{
			flag=1;
			return;
		}
		if(sum>B)
		{
			if(minlen!=0)
			{
				if(sum-B<minlen)
				minlen=sum-B;
			}
			else
			minlen=sum-B;
			return;
		}
	}
	for(int i=0;i<n;i++)
	{
		if(v[i]==0&&i>last)
		{
			v[i]=1;
			sum+=stick[i];
			dfs(i);
			sum-=stick[i];
			v[i]=0;
		}
	}
} 
 
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		cin>>n>>B;
		for(int i=0;i<n;i++)
		cin>>stick[i];
		sum=0;
		for(int i=0;i<n;i++)
		v[i]=0;
		flag=0;
		minlen=0;
		dfs(-1);
		if(flag==1)
		{
			cout<<B<<endl;
			continue;
		}
		cout<<minlen+B<<endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值