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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章