hdu 1455 Sticks(dfs+可行性剪枝)

来源:互联网 发布:java加泛型的方法 编辑:程序博客网 时间:2024/05/29 08:33

Sticks

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


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
65
 

Source
ACM暑期集训队练习赛(七)
题目分析:枚举原始木棒的数量,然后利用深搜判断当前解时候合法,按照从大到小的顺序,如果合法,直接输出
 在进行深搜时,当某一个木棒作为一根原始木棒的第一节或者最后一节时都不能成功得到木棒的时候,在当前情况下,就没有继续向下搜索的必要了
因为之后这根木棒一定会落单,不能够组成原始木棒
#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#define MAX 107using namespace std;int n;int a[MAX];bool used[MAX];int sum;bool flag;void dfs ( int num , int m , int cnt , int total ){    if ( num > sum/total ) return;    if ( m == n && cnt == total )    {        flag = true;        return;     }    for ( int i = n ; i > 0 ; i-- )    {        if ( used[i] ) continue;        used[i] = true;        if ( num+a[i] == sum/total ) dfs ( 0 , m+1 , cnt+1 , total );        else dfs ( num+a[i] , m+1 , cnt , total );        used[i] = false;        if ( flag ) return;        if ( num == 0 || num+a[i] == sum/total ) break;    }}int main ( ){    while ( ~scanf ( "%d" , &n ),n )    {        sum = 0;        for ( int i = 1 ; i <= n ; i++ )        {           scanf ( "%d" , &a[i] );           sum += a[i];        }        sort ( a+1 , a+n+1 );        flag = false;        for ( int i = n ; i > 0 ; i-- )        {            memset ( used , 0 , sizeof ( used ) );            if ( sum%i == 0 )            {                flag = false;                dfs ( 0 , 0 , 0 , i );                if ( flag )                {                    printf ( "%d\n" , sum/i );                    break;                }            }        }     }}


0 0