您的位置:首页 > 其它

poj 1011 sticks (dfs + 剪枝)

2017-03-18 16:11 393 查看
Sticks

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 143202 Accepted: 33827
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
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>

#include<algorithm>
using namespace std;

int a[100];
int vis[100];

int n;

int cmp(int a,int b)
{
return a > b;
}

int dfs(int cur, int len, int pos, int cnt  )  // 当前还需要的长度
{
//	printf("cur = %d ,len = %d ,pos = %d ,cnt = %d\n",cur,len,pos,cnt);

if( cnt == n )
return 1;

int tmp = -1;

for(int i = pos; i < n; i ++)
{

if( vis[i] == 1 || a[i] == tmp)
continue;

vis[i] = 1;

if( a[i] < cur)
{

if( dfs( cur - a[i], len, i  ,cnt + 1 ) == 1)
return 1;

else tmp = a[i];

}

else if( a[i] == cur)
{

if( dfs( len, len, 0, cnt + 1) == 1)
return 1;

else  tmp = a[i];
}

vis[i] = 0;

if( cur == len)  // 当某次搜索的第一次,没有搜到可以组成 目标长度时,直接停止,
//  因为第一个搜不到,后面的搜到了,也没有用
break;
}
return 0;

}
int main()
{
int sum = 0;
int maxn = -1;

while(~scanf("%d",&n),n)
{
sum = 0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum += a[i];
}

sort(a,a+n,cmp);
maxn = a[0];    // 找最大的数不能放在输入中,会 wa

memset(vis,0,sizeof(vis));

int flag = 0;

for(int i = maxn; i <= sum ; i++)  // 从 maxn 到 sum  遍历一遍
{
if( sum % i != 0)
continue;

//	memset(vis,0,sizeof(vis));

if( dfs( i, i, 0, 0) )
{
flag = 1;
printf("%d\n",i);
break;
}
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: