OutputThe output file contains the smallest possible length of original sticks, one per line.
Sample Input
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0Sample Output
6 5
解題思路:
這其實就是dfs,但是直接dfs就會超時,要去剪枝,將所有的樹枝排序,如果第一個是不符合的,比如說需要達到的長度是10,當前的長度是8,但是後面序列裏,並沒有長度爲2的,那麼8後面的情況都不需要考慮了,然後還有一些基礎的剪枝
代碼:
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100];
int sum,maxx;
int t;
bool flag;
int vis[100];
bool cmp(int a,int b)
{
return a>b;
}
int dfs(int need,int now,int pos,int num)
{
if(flag)
{
return true;
}
if(num==t)
{
flag = true;
return true;
}
for(int i = pos;i<t;i++)
{
if(!vis[i]&&a[i]+now<=need)
{
vis[i] = 1;
if(now+a[i]==need)
dfs(need,0,0,num+1);
else dfs(need,a[i]+now,i+1,num+1);
vis[i] = 0;
if(now==0)
return false;
while(i+1<t&&a[i]==a[i+1])
i++;
if(flag)
return true;
}
}
}
int main()
{
while(cin>>t&&t!=0)
{
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
flag = false;
sum = 0;
maxx = 0;
for(int i = 0;i<t;i++)
{
cin>>a[i];
sum+=a[i];
maxx = max(maxx,a[i]);
}
sort(a,a+t,cmp);
if(maxx>sum-maxx)
{
cout<<sum<<endl;
continue;
}
for(int i = maxx;i<=sum;i++)
{
if(sum%i==0)
{
dfs(i,0,0,0);
if(flag)
{
cout<<i<<endl;
break;
}
}
}
}
}