您的位置:首页 > 编程语言

[POJ][1011]Sticks

2014-05-14 17:03 281 查看
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


这个题目就是一个DFS可以完成,但是暴力搜索肯定会TLE,需要剪枝,下面说一下思路和处理方法

1.获得剪断的木棍长度数组之后首先降序排列,因为木棍越长,约束越大,这样我们剪枝的地方就接近根部
2.木棍的总长度除以原来的木棍数量,一定可以整除,剪枝
3.原来木棍的长度,一定大于等于剪短后最长的木棍,剪枝
4.在搜索的时候,如果发现某根木棒不符合要求,那么跳过之后与其等长的木棍,剪枝
5.如果新组合的木棍无法组合成功,那么直接放弃搜索,回退到上一层,剪枝
6.如果已经成功组合了一部分木棍,剩下的无法组合成功,由于是降序排列,直接放弃,返回上一层,剪枝

上面5和6的剪枝最关键的是5,我原来的代码一直TLE,加上5之后马上就AC了

下面是AC代码

#include <cstdio>
#include <cstdlib>
using namespace std;
int num=0,targetlen;
int* arrayptr;
bool* used;

int compare (const void * a, const void * b)
{
return ( *(int*)b - *(int*)a );
}

bool find(int curlen, int start, int left)
{
if(left==0) return true;
if(used[start]==true)
{
while (used[start]) start++;
return find(curlen,start,left);
}
int same = -1;
if (curlen == targetlen) curlen=0;
for(int i=start;i<num;i++)
{
if(used[i] || arrayptr[i] == same) continue;
if(arrayptr[i]==(targetlen-curlen)) {
used[i]=true;
if (find(0, 0, left-1))
{
return true;
}
else
{
used[i]=false;
break;
}
}
else if(arrayptr[i]<(targetlen-curlen))
{
used[i]=true;
if(find(curlen+arrayptr[i], i+1, left-1))
{
return true;
}
else
{
used[i]=false;
same=arrayptr[i];
}
}
if (curlen==0) break;
}
return false;

}

int main()
{
scanf("%d",&num);
while(num != 0)
{
arrayptr = new int[num];
used = new bool[num];
int sum=0;
int largest=-1;
for(int i=0;i<num;i++)
{
scanf("%d",&arrayptr[i]);
if(arrayptr[i]>largest) largest = arrayptr[i];
sum += arrayptr[i];
used[i] = false;
}
qsort(arrayptr, num,sizeof(int), compare);
for(int i=num;i>=1;i--)
{
if(sum % i == 0 && sum/i>=largest)
{
targetlen = sum/i;
if(find(0, 0, num))
{
printf("%d\n",targetlen);
break;
}
}
}
delete[] arrayptr;
delete[] used;
scanf("%d",&num);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索 dfs poj 源代码