题目网址:http://poj.org/problem?id=1011
题目:
Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 136183 Accepted: 32056
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
题意:
给你一堆长度不等的棍子,拼接他们,获得长度相等的几组棍子,请问拼接的最短长度是多少?
思路:
啊,深度优先搜索可以解决这道题。将得到的木棍的长度从大到小排序,然后我们从最大的开始一个一个搜索,有以下的一些小技巧:
1. 最大的往最小的开始找,
2. 相同的,不能找到的,就不用重复搜索了
3. 我们枚举的长度一定要比最大长度长
4. 我们枚举的长度一定要能够被总长度整除
5. 如果有最长的没有成功的,比它短的也不一定可以成功,因为题目都会用到,所以就必要继续搜索下去了。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
using namespace std;
bool used[65]; //状态标记量
int sticks[65];
int length, sum, L;
bool cmp(int a, int b)
{
return a > b;
}
bool DFS(int m, int temp)
{
if(m == 0 && temp == 0)
{
return true;
}
if(temp == 0)
{
temp = L;
}
for(int i = 0; i < length; i++)
{
if(!used[i] && sticks[i] <= temp)
{
if(i > 0) // 相同木棒剪枝
{
if(!used[i-1] && sticks[i] == sticks[i-1])
{
continue;
}
}
used[i] = true;
if(DFS(m-1, temp-sticks[i]))
{
return true;
}
else{ //最长的长度匹配失败,比它短的也会失败,没意义的搜索
used[i] = false;
if(temp == sticks[i] || temp == L)
return false;
}
}
}
return false;
}
int main()
{
while(scanf("%d", &length) != EOF && length)
{
sum = 0;
for(int i = 0; i < length; i ++)
{
scanf("%d", &sticks[i]);
sum += sticks[i];
used[i] = 0;
}
sort(sticks, sticks+length, cmp);
for(L = sticks[0]; L <= sum/2; L++)
{
if(sum % L)
{
continue;
}
memset(used, false, sizeof(used));
if(DFS(length, L))
{
cout << L << endl;
break;
}
}
if(L > sum/2)
{
cout << sum << endl;
}
}
return 0;
}