hdu--1455--DFS(难度一般)

来源:互联网 发布:知乎娱乐圈猛料2017 编辑:程序博客网 时间:2024/05/18 21:08

Sticks

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


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
95 2 1 5 2 1 5 2 141 2 3 40
 

Sample Output
6
5
 
 
 
 
#include <iostream>#include <algorithm>using namespace std;int total,L;int num,sum;typedef struct{    int length;    bool mark;}Sticks;Sticks sticks[70];bool cmp(Sticks a,Sticks b){    return a.length>b.length;}//s 已组成的木棒数目,len已经组成的长度,pos搜索的木棒的下标的位置int dfs(int s,int len,int pos)  //(1,0,-1){    if(s==total)return 1;    for(int i=pos+1;i<num;i++)    {                if(sticks[i].mark)continue;        if(len+sticks[i].length == L)        {            sticks[i].mark = true;            if(dfs(s+1,0,-1)){            return true;            }            sticks[i].mark = false;            return false;        }else if(sticks[i].length+len<L){            sticks[i].mark = true;            if(dfs(s,len+sticks[i].length,i)){             return true;            }            sticks[i].mark = false;                       if(len==0)return false;                     while(sticks[i].length==sticks[i+1].length)i++;        }    }    return false;}int main(){    while(scanf("%d",&num)&&num!=0)    {        sum = 0;        for(int i = 0; i < num; i++)        {        scanf("%d",&sticks[i].length);                    sum += sticks[i].length;            sticks[i].mark = false;        }               sort(sticks,sticks+num,cmp);               for(L = sticks[0].length; L <= sum; L++)        {                     if(sum%L!=0)continue;            total = sum / L;            if(dfs(1,0,-1))            {                printf("%d\n",L);                break;            }        }    }    return 0;}

原创粉丝点击