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