hdu 题目1445 Stick(DFS+剪枝)

 

 

 

Sticks

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4753    Accepted Submission(s): 1316


Problem 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 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 0


 

Sample Output
6 5
 

黑书P181上面有分析

DFS+剪枝

参考黑书分析之后的个人算法:

1.初始木棍的长度必须是所有木棍长度之和的约数

2.按木棍的递减顺序搜索

3.构造一根初始木棍的第一根木棍必须是最长的

4.2根长度相同的木棍没必要重复搜索

 

 

#include<stdio.h>
#include<algorithm>
#include<string.h>
int n,a[66],sum; bool vis[66];
int cmp(const void* a,const void *b)
{
	return *(int *)b - *(int *)a;
}
bool dfs(int x,int p,int len,int num)//num代表当前找到的边长数目,len代表要找的长度 
{
    bool flag; //标记是否找到符合题意的 
    if(num==sum/len-1) return 1; //需要找到的数目为 sum/len ,只需找到 sum/len-1剩下的一定是组合成一根 
    for(int i=p+1;i<=n;i++)	
        if(!vis[i] && x>=a[i]) 
        {
            vis[i]=1;
            if (x==a[i]) flag = dfs(len,0,len,num+1); //找到一根,x复原 
            else flag = dfs(x-a[i],i,len,num); //找到一根len长的还需要 x-a[i] 长度 
            vis[i]=0;
            if (p==0) return flag;//当搜索返回到最开始的一层时, 
            else if (flag) return 1;
            while (a[i]==a[i+1]) i++;//相同的木棍不需要再继续判断 
        }	
		return 0;
}
int main()
{
	while(scanf("%d",&n),n)
	{
		int i;  sum=0;
		for(i=1;i<=n;i++){
			scanf("%d",&a[i]);
			sum += a[i];
		}
		qsort(a+1,n,sizeof(int),cmp); //按递减序列进行查找 
		memset(vis,0,sizeof(vis)); 
		int ans = sum;
		for(i=a[1];i<=sum/2;i++)
			if(sum%i==0 && dfs(i,0,i,0)){ ans = i; break; }
		printf("%d\n",ans);
	}
	return 0;
}