一道acm 题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 originall

来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/22 21:36:31
一道acm题Georgetooksticksofthesamelengthandcutthemrandomlyuntilallpartsbecameatmost50unitslong.Nowhewan

一道acm 题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 originall
一道acm 题
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 ( < 100 ).The second line contains the lengths of those parts separated by the space.The last line of the input contains zero.
Output
The output 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
Hint:You can ignore the parts which more than 50 units long.

一道acm 题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 originall
#include
#include
#include
using namespace std;
bool flag[99];
int a[100],m,cnt,n;
bool DFS(int x,int rest,int step)
{
if (step == cnt) return true;
for (int i = x; i < n; ++i)
if (!flag[i])
{
if (a[i] == rest)
{
flag[i] = true;
if (DFS(0,m,step + 1)) return true;
return flag[i] = false;
}
else if (a[i] < rest)
{
flag[i] = true;
if (DFS(x + 1,rest - a[i],step)) return true;
flag[i] = false;
if (rest == m) return false;
while (a[i] == a[i + 1]) ++i;
}
};
return false;
}
int main()
{
int a_max,sum;
while (scanf("%d",&n),n)
{
a_max = 0; sum = 0;
for (int i = n; i; )
{
scanf("%d",&a[--i]);
sum += a[i];
if (a[i] > a_max) a_max = a[i];
}
sort(a,a + n,greater());
for (m = a_max; m < sum; ++m)
if (sum % m == 0)
{
memset(flag,false,n);
cnt = sum / m;
if (DFS(0,m,1))
{
printf("%d\n",m);
goto NEXT;
}
};
printf("%d\n",sum);
NEXT:;
}
return 0;
}

深度搜索
强剪枝

跟北大的一个题目一样啊