Sticks_dfs

Description

George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.

Input

The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.

Output

The output should 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
0

Sample Output

6
5

【题意】给出n个长度的短棒,是由原来等长的小棒任意剪切而来,问原来的小棒最短的长度是多少

【思路】用dfs搜索,重点是其中的几个剪枝,不减的话会超时。

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int N=;
int n;
int d,num;
int val[N];
int vis[];
bool flag;
int cmp(int x,int y)
{
return x>y;
}
void dfs(int k,int len,int num1)
{
if(flag==) return ;
if(len==d)
{
dfs(,,num1+);
if(flag==) return ;
}
if(num1==num)
{
flag=;
return ;
}
for(int i=k;i<=n;i++)
{
if(!vis[i]&&len+val[i]<=d)
{
vis[i]=;
dfs(i+,len+val[i],num1);
vis[i]=;
if(len==) return ;

//如果当前搜索时,前面的长度为0,而第一根没有使用,说明第一根始终要废弃,这种组合必然不会成功

            if(len+val[i]==d) return ;
if(val[i]==val[i+]) i++;

//如果当前和上一次搜到的木棒一样长,就没必要再搜了

        }
} }
int main()
{
while(~scanf("%d",&n),n)
{
int sum=;
for(int i=;i<=n;i++)
{
scanf("%d",&val[i]);
sum+=val[i];
}
sort(val+,val++n,cmp);
for(int i=val[];i<=sum;i++)
{
if(!(sum%i))
{
flag=;
memset(vis,,sizeof(vis));
d=i;
num=sum/d;
dfs(,,);
if(flag==) break;
}
}
printf("%d\n",d);
} return ;
}
上一篇:UITableView设置Cell左滑多个按钮(编辑,删除,置顶等)


下一篇:Js 赋值传值和引用传址