Sticks --UVA

来源:互联网 发布:springmvc ajax json 编辑:程序博客网 时间:2024/05/16 09:51

Sticks

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 

5 2 1 5 2 1 5 2 1 

1 2 3 4 

Sample Output 

5
题意: 给出一定数量的小木棒的长度,它是由等长的若干木棒随

意砍断所得到的。对于给定的一组小木棒,请求出原始木棒的最

小长度。

思路:主要注意的是剪枝,需要剪三次,并且在搜之前要排序。

第一次:搜原始木棒的长度时,sum必须是它的倍数。

第二次:如果一个木棒与前一个木棒长度相等,并且前一个已经

搜过且不符合题意,那么这个就不需要再搜了。

第三次:如果后面不符合题意,那么前面我们连的木棒需要拆
分。
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int n,sum,m,k;       //n木棒数量,m为原始的木长 ,k为原始木长int a[100];          //sum为木棒总长度。int book[100];int cmp(int a,int b){    return a>b;}int dfs(int len,int s,int j)//len此前连接木棍的长度{    //j表示从j点开始向下搜。    //s为连接好木棍的数量,    if(len==m)    {        s++;        j=0;        len=0;    }    if(s==k)        return 1;    for(int i=j+1; i<n; i++)    {        if(book[i]||a[i]==a[i-1]&&!book[i-1]&&i>0)            continue;        if(a[i]+len>m)            continue;        book[i]=1;        if(dfs(len+a[i],s,i))            return 1;        book[i]=0;        if(len==0)     //后面的不符合题意,则前面连接好的木棒需要拆分。            return 0;    }    return 0;}int main(){    while(~scanf("%d",&n),n)    {        sum=0;        for(int i = 0; i < n; i++)        {            scanf("%d",&a[i]);            sum += a[i];        }        sort(a,a+n,cmp);        for(m= a[0]; m <= sum/2; m++)        {            memset(book,0,sizeof(book));            if(sum % m != 0)                continue ;            k=sum/m;            book[0]=1;            if(dfs(a[0],0,0))            {                printf("%d\n",m);                break;            }        }        if(m>sum/2)            printf("%d\n",sum);    }    return 0;}


原创粉丝点击