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 sticks each with some length of . I want to use those sticks to make a longer stick with length longer than or equal to . Furthermore, I want the length of the stick as close to as possible.
Task
Now, it is your turn. I will tell you the length of those sticks, and . 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 ,the number of test cases. There are two lines for each test case. The first line contains two integer numbers and . The second line contains integer numbers(the length of sticks I have already, ).
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;
}