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.
The input file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.
The output file contains the smallest possible length of original sticks, one per line.
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
6 5
题目大意:本来有m根长为l等长的木棒,将其分别切成若干段之后(可能切,可能没切),忘记了原来的长度l,求最短的长度l。
(转)
①先将木棒长度从大到小进行排序,这样便于后面的选择和操作,是后面一些剪枝算法的前提。
②在枚举原木棒长度时,枚举的范围为max与sum/2之间,如果这个区间内没有找到合适的长度,那么最后原木棒的长度只能是sum。
③枚举的原木棒的长度只能是sum的约数。
④在深搜过程中,如果当前木棒和前一个木棒的长度是一样的,但是前一个木棒没有被选上,那么这个木棒也一定不会被选上。
⑤在深搜过程中,如果当前是在拼一根新木棒的第一截,但如果把可用的最长的一根木棒用上后不能拼成功的话,那么就不用再试后面的木棒了,肯定是前面拼的过程出了问题。
⑥在深搜过程中,如果当前可用的木棒恰好能补上一根原木棒的最后一截,但用它补上之后却不能用剩下的木棒完成后续的任务,那么也不用再试后面的木棒了,肯定是前面拼的过程出了问题。
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<algorithm> using namespace std; int s[100], n, sum, L, vis[100], cnt, ans, num, len; int cmp(int a, int b) { return a > b; } int DFS(int l, int d, int c) { if (l == L) { //拼凑木条或原木条等于要求长度 c++; //完成木条数加一 if (c == num) { //完成木条数等于当前需求木条数,获取最小木条数 if (ans > c) ans = c; return 1; } else { for (d = 0; vis[d]; d++); //找寻没使用过的木条 vis[d] = 1; if (DFS(s[d], d + 1, c)) return 1; vis[d] = 0; } } else { for (int i = d; i < n; i++) { if (!vis[i] && s[i] <= L - l) { if (i != 0 && s[i] == s[i - 1] && !vis[i - 1]) continue; //如果前一个木条没有访问过,下一个相同的木条也无需访问 vis[i] = 1; if (DFS(l + s[i], i + 1, c)) return 1; vis[i] = 0; if (s[i] == L - l) return 0; //后续木棒不能再用,有剩余 } } } return 0; } int main() { while (scanf("%d", &n) == 1, n) { memset(vis, 0, sizeof(vis)); cnt = 0; sum = 0; for (int i = 0; i < n; i++) { scanf("%d", &s[i]); sum += s[i]; } sort(s, s + n, cmp); ans = 0xFFFFFFFF; for (L = s[0]; L <= sum / 2; L++) { //找出因子,进行DFS if (sum % L != 0) continue; else { num = sum / L; if (DFS(0, 0, 0)) break; } } if (L <= sum / 2) { printf("%d\n", L); } else printf("%d\n", sum); } return 0; }
原文地址:http://blog.csdn.net/llx523113241/article/details/43486005