POJ 1011 Sticks

来源:互联网 发布:php双轨直销系统源码 编辑:程序博客网 时间:2024/05/17 02:28
Sticks
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 109705 Accepted: 25147

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

95 2 1 5 2 1 5 2 141 2 3 40

Sample Output

65

Source

Central Europe 1995
 
题意:
给定不同长度的木棍,求其可组成的相同长度的最短的木棍长度
 
代码:
#include<cstdio>#include<cstring>#include<cstdlib>int stick[65];bool visited[65];int n,sum,max,init;int cmp(const void *a,const void *b){return *(int *)b-*(int *)a;}bool search(int len,int s,int num)          //当前所接木棍总长度为len,从第s根木棍开始计算,已用n根木棍{if(num==n) return true;int flag=-1;                            //剪枝:相同长度的木棍只搜索一次for(int i=s;i<n;i++){if(visited[i] || flag==stick[i]) continue;visited[i]=true;if(len+stick[i]<init){if(search(len+stick[i],i+1,num+1))return true;}else if(len+stick[i]==init){if(search(0,0,num+1))return true;}visited[i]=false;flag=stick[i];if(len==0) return false;              //剪枝:构建新棒是,对于第一根木棍,其余的所有木棍都无法与其组合                                      //则说明该init长度不合适,不必继续往下搜索,直接返回上一层}return false;}int main(){int i,flag;while(scanf("%d",&n)!=EOF && n){sum=0;for(i=0;i<n;i++){scanf("%d",&stick[i]);sum+=stick[i];}memset(visited,false,sizeof(visited));qsort(stick,n,sizeof(int),cmp);max=stick[0]; flag=0;for(init=max;i<=sum-init;init++)           //剪枝:若能在[max,sum-init]找到最短的init,该init必也是[max,sum]的最短{if(sum%init==0 && search(0,0,0))       //剪枝:init必为sum的约数{printf("%d\n",init);flag=1;break;}}if(flag==0) printf("%d\n",sum);}return 0;}

思路:
与POJ 2362类似,但需考虑所组成木棍的长度

若init为所求的最短原始棒长,max为给定的木棍中最长的木棍,sum为这堆棒子的长度之和,那么init必定在范围[max,sum]中

深度搜索前需对木棍进行倒序排序

注意代码注释中的剪枝方法

 

原创粉丝点击