sticks(深搜剪枝)

来源:互联网 发布:阳光下的星星 知乎 编辑:程序博客网 时间:2024/05/21 07:14
Sticks
Time Limit: 1000MS Memory Limit: 10000KTotal 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

95 2 1 5 2 1 5 2 141 2 3 40

Sample Output

65
思路:(各种转载)转自acm课件以及http://blog.sina.com.cn/s/blog_520db5ec0100copn.html
1
长度最好从最长的木棍开始试,因为它是灵活度最低的
剪枝:
第二种:
第一跟木棍不符合条件,那么就不用再判断这组木棍能不能拼成了。因为在所有剩下的木棍里,总会有这第一根,不符合条件的木棍存在,坑爹吧
第三种:
如果回溯到上一组,那么上一组的最后一根也不要再考虑其他情况,因为替换好的长度在下面还是会出现,依旧是不符合的
第四种:
总结:
代码:
 #include<stdio.h>#include<string.h>#include<stdlib.h>#define N 200int 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;}        


                                             
0 0
原创粉丝点击