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
#include<set>
#include<map>
#include<stack>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int maxn = 1e3 + 5;
int n, cnt, len;
int a[maxn],sum,vis[maxn];
int cmp(int x, int y)
{
return x > y;
}
int dfs(int num, int val)
{
if (num == cnt) //当num等于剪切的段数时返回
return 1;
if (val == len) //当val=len时开始下一个搜索
return dfs(num + 1, 0);
int temp = 0;
for (int i = 1; i <= n; i++)
{
if (!vis[i] && val + a[i] <= len)
{
vis[i] = 1;
if (dfs(num, val+a[i]))
return 1;
vis[i] = 0;
if(val == 0 || val + a[i] == len)//剪枝 代表不能将所有的拼出len 直接返回0
return false;
}
}
return 0;
}
int main()
{
while (std::cin >> n && n)
{
sum = 0;
for (int i = 1; i <= n; i++)
{
std::cin >> a[i];
sum += a[i];
}
std::sort(a+1, a + n+1,cmp); //排序 用于剪枝
for (int i = a[1]; i <= sum; i++) //从a数组最大的数开始遍历 到sum停止
{
if (sum % i != 0) continue;
cnt = sum / i;
len = i;
memset(vis, 0, sizeof(vis));
if (dfs(0,0))
{
std::cout << i << std::endl;
break;
}
}
}
return 0;
}
博客讲述 George 将等长木棍随机切割,各部分最长 50 单位,他想恢复原状却忘了原数量和长度。需设计程序计算原木棍最小可能长度,输入为切割后木棍数量及各部分长度,输出为原木棍最小长度。
321

被折叠的 条评论
为什么被折叠?



