POJ 1011 (DFS)

来源:互联网 发布:一元云购v8源码 编辑:程序博客网 时间:2024/06/05 06:49

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

题解:看代码中注释

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <map>#include <queue>#include <cmath>#include <vector>using namespace std;const int maxn = 70;int n, l[maxn], sum, flag, vis[maxn];int cmp(int a, int b) {    return a > b;}bool DFS(int num, int nl, int rel, int now)//num为已经用过的小棒数目,nl为现在已经有多长,rel是总共要组合成多长,now是现在已经搜索到哪根棒了{    if (num == n) return true;    int sample = -1;    for (int i = now; i < n; i++) {        if (vis[i] || l[i] == sample) continue;//剪枝第三刀:等长的只搜索一次        vis[i] = 1;        if (nl + l[i] < rel) {            if (DFS (num + 1, nl + l[i], rel, i)) return true;            else sample = l[i];        } else if (nl + l[i] == rel) {            if (DFS (num + 1,  0, rel, 0)) return true;//还要把原来跳过的等长的再看一遍,考虑一遍            else sample = l[i];        }        vis[i] = 0;        if (nl == 0) break;//剪枝第四刀:如果没有配对的,就跳出去    }    return false;}int main(){    #ifndef ONLINE_JUDGE    freopen ("in.txt", "r", stdin);    #endif // ONLINE_JUDGE    while (scanf ("%d", &n) != EOF) {        if (n == 0) break;        sum = 0;        flag = 0;        memset (l, 0, sizeof(l));        for (int i = 0; i < n; i++) {            scanf ("%d", &l[i]);            sum += l[i];        }        sort (l, l + n, cmp);        for (int i = l[0]; i <= sum / 2 + 1; i++) {//剪枝第一刀:下限为最长的棍长,上限是一半多一个            if (sum % i != 0) continue;//剪枝第二刀:如果不是总长度的余数            memset (vis, 0, sizeof(vis));            if (DFS (0, 0, i, 0)) {                flag = 1;                printf ("%d\n", i);                break;            }        }        if (flag == 0) printf ("%d\n", sum);    }    return 0;}
0 0