Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 115807 | Accepted: 26640 |
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.
策略:
1.求所有短木棒的长度的最大值,长木棒长度必大于等于该值;
2.求所有短木棒长度之和,长木棒长度一定能被该值整除;
3.将短木棒长度序列按降序排列,拼凑长木棒时优先取较长的短木棒;
4.如果stick[i]失败,那么如果stick[i+1] == stick[i],stick[i+1]也一定失败,跳过;
5.在拼凑一个新的长木棒时,如果所取的第一个短木棒就失败,那么意味着凭余下的短木棒不可能拼凑出长木棒。因为在取第一个短木棒时,该棒可以和当前可用的所有其他短木棒组合,如果这样都失败,意味根本不可能成功。直接返回上一层。
AC Code:
策略:
1.求所有短木棒的长度的最大值,长木棒长度必大于等于该值;
2.求所有短木棒长度之和,长木棒长度一定能被该值整除;
3.将短木棒长度序列按降序排列,拼凑长木棒时优先取较长的短木棒;
4.如果stick[i]失败,那么如果stick[i+1] == stick[i],stick[i+1]也一定失败,跳过;
5.在拼凑一个新的长木棒时,如果所取的第一个短木棒就失败,那么意味着凭余下的短木棒不可能拼凑出长木棒。因为在取第一个短木棒时,该棒可以和当前可用的所有其他短木棒组合,如果这样都失败,意味根本不可能成功。直接返回上一层。
AC Code:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int sticks[65];
bool used[65];
int usedCnt;
int ans;
int n;
bool cmp (const int& a, const int& b)
{
return a > b;
}
bool dfs (int x, int sum)
{
//用完n个短木棒,全部长木棒还原成功
if (usedCnt == n)
return true;
//尚未用完n个木棒但是已经还原出一个新的长木棒
//开始新一轮的还原
if (sum == ans)
{
sum = 0;
}
++usedCnt;
int i;
for (i = 0; i < n; ++i)
{
if (sticks[i] + sum <= ans && !used[i])
{
used[i] = true;
if (dfs (i + 1, sticks[i] + sum))
return true;
else
{
used[i] = false;
if (sum == 0)
break;
//i失败,那么紧接i的与i同值的元素也必失败,跳过
int tmp = sticks[i];
for (; i < n && sticks[i] == tmp; ++i) {}
--i;
}
}
}
--usedCnt;
return false;
}
int main()
{
while (scanf("%d", &n) && n)
{
int sum = 0;
for (int i = 0; i < n; ++i)
{
scanf("%d", &sticks[i]);
sum += sticks[i];
}
sort (sticks, sticks + n, cmp);
for (ans = sticks[0]; ; ++ans)
{
if (sum % ans) continue;
usedCnt = 0;
memset (used, false, sizeof(used));
if (dfs(0, 0))
break;
}
printf("%d\n", ans);
}
return 0;
}