CC

自然万物都趋向从有序变得无序

0%

Sticks POJ - 1011

题目链接:点这里

题目

    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 smal
lest 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

题意:

   给你一堆长度的棍子,他们是由一些长度相同的棍子切割而来,求最初的最短棍子长度

思路:

棍子长度最小是题目中给的最初的那个,最长是题目中所有的棍子长度的总和. 因此暴力枚举可能的棍子长度,对于每个棍子长度进行搜索,判断能否切割成题目所给出的棍子长度

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int a[70];
int n;
bool vis[70];

int dfs(int len,int rres,int num)
{
if(num==0&&rres==0)
return len;
if(rres==0)//每一次当剩余的长度为0时都要重新赋值
rres=len;
for(int i=n;i>=1;--i)
if(!vis[i]){
if(rres>=a[i]){
vis[i]=true;
if(dfs(len,rres-a[i],num-1))
return len;
vis[i]=false;
if(rres-a[i]==0||len==rres)
break;
while(a[i]==a[i-1]) --i;
}
}
return 0;
}
int main()
{
while(scanf("%d",&n)!=EOF&&n){
int sum=0;
for(int i=1;i<=n;++i){
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a+1,a+1+n);
int ans;
for(int i=a[n];i<=sum;++i) //枚举可能的棍子长度
if(sum%i==0){ //明显只有sum能整除i的时候才能切割
memset(vis,false,sizeof(vis));
ans=dfs(i,0,n);
if(ans)
break;
}
cout<<ans<<endl;
}
return 0;
}