sticks(深搜剪枝)

Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 113617 Accepted: 26102

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
 
思路:(各种转载)转自acm课件以及http://blog.sina.com.cn/s/blog_520db5ec0100copn.html
1
长度最好从最长的木棍开始试,因为它是灵活度最低的

剪枝:

第二种:
	第一跟木棍不符合条件,那么就不用再判断这组木棍能不能拼成了。因为在所有剩下的木棍里,总会有这第一根,不符合条件的木棍存在,坑爹吧
第三种:
	如果回溯到上一组,那么上一组的最后一根也不要再考虑其他情况,因为替换好的长度在下面还是会出现,依旧是不符合的
第四种:
	
	
总结:

 
代码:
 #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 200
int stick[N], mark[N], flag;
int n;
int sum, L;//sum:木棒的总数, L:假设的长度
int  cmp(const void* a, const void *b);

void dfs(int r, int m, int p){// r:剩余木棍数量,m:剩余长度,p:从第几根木棍开始测试
	int i, state = -1;

	if(r == 0 && m == 0){			
		flag = 1;
		return;
	}
	if(m == 0){//拼完一根拼下一根
		m = L;
		p = 0;
	}
	if(r > 0 && !flag){
		for(i = p; i < n; i++){//剪枝4:保证了拼每一根只从其后面的,即比它长度小的开始遍历
			if(mark[i] == 0 && stick[i] != state && stick[i] <= m){	
				mark[i] = 1; 
				dfs(r - 1, m - stick[i], i+1);			
				state = stick[i];//剪枝1:如果退回这里就说明i木棍是不符和条件的,下次就不需要在这个位置判断这根木棍
				mark[i] = 0;
				if(m == L)//剪枝2,3:第一根或最后一根木棒不符合条件就不需要再对这根木棒进行尝试
					break;
			}
		}		
	}
}

int main()
{
	int i;

	while(scanf("%d",&n) && n){	
	
		flag = sum = 0;
		//memset(stick, 0,sizeof(stick));
		for(i = 0; i < n; i++){
			scanf("%d", &stick[i]);
			sum += stick[i];
		}
		

		qsort(stick, n, sizeof(stick[0]), cmp);//由大到小排序

		for(L = stick[0]; L <= sum; L++){

			if(sum % L == 0){
				memset(mark, 0, sizeof(mark));		
				dfs(n, L, 0);		
				if(flag == 1){
					printf("%d\n", L);
					break;
				}
			}
		}
	}
	return 0;
}

int  cmp(const void* a, const void *b){//从大到小排序

	return *(int *)b - *(int *)a;
}        



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值