1. 程式人生 > >poj 1011 Sticks

poj 1011 Sticks

urn contains left sum 設計 align arch tin 可能

                        Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 150282 Accepted: 35746

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

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output

6
5

Source

Central Europe 1995 翻譯: 喬治拿來一組等長的木棒,將它們隨機地砍斷,使得每一節木棍的長度都不超過50個長度單位。然後他又想把這些木棍恢復到為裁截前的狀態,但忘記了初始時有多少木棒以及木棒的初始長度。請你設計一個程序,幫助喬治計算木棒的可能最小長度。每一節木棍的長度都用大於零的整數表示。

輸入包含多組數據,每組數據包括兩行。第一行是一個不超過64的整數,表示砍斷之後共有多少節木棍。第二行是截斷以後,所得到的各節木棍的長度。在最後一組數據之後,是一個零。

為每組數據,分別輸出原始木棒的可能最小長度,每組數據占一行。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int stick[100], n;
bool used[100];
int cmp(int x,int y){
    return x>y;
}
bool dfs(int unused,int left,int len){
    if(unused==0&&left== 0)    return true;
    if(left==0)    left=len;
    for(int i=0;i<n;i++){ 
        if(!used[i]&&stick[i]<=left){
            used[i]=true;
            if(dfs(unused-1,left-stick[i],len))    return true;
            used[i]=false;
            if(stick[i]==left||left==len)    break;
        }
    }
    return false;
}  
int main(){
    int sum;
    while(scanf("%d",&n)!=EOF&&n){
        sum=0;
        for(int i=0;i<n;++i){
            scanf("%d",&stick[i]);
            used[i]=false;
            sum+=stick[i];
        }
        sort(stick,stick+n,cmp);
        for(int i=stick[0];i<=sum;++i)
            if(sum%i==0)
                if(dfs(n,0,i)){
                    printf("%d\n", i);
                    break;
                }
    }
    return 0;
}

poj 1011 Sticks