Olympiad in Informatics

POJ1011: Sticks — Solution & a Classic Pruning Example

Pruning Techniques

The pruning techniques in this problem are very ingenious, and many of them can be put to good use when solving problems. I'll post the code first, and then we'll analyze it.

// POJ1011.cpp
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 70;
int n, arr[maxn], stcnt, len;
bool vis[maxn];
bool cmp(int a, int b) { return a > b; }
bool dfs(int st, int cab, int last)
{
    if (st > stcnt)
        return true;
    if (cab == len)
        return dfs(st + 1, 0, 1);
    int fail = 0;
    for (int i = last; i <= n; i++)
        if (fail != arr[i] && cab + arr[i] <= len && !vis[i])
        {
            vis[i] = true;
            if (dfs(st, cab + arr[i], i + 1))
                return true;
            fail = arr[i];
            vis[i] = false;
            if (cab == 0 || cab + arr[i] == len)
                return false;
        }
    return false;
}
int main()
{
    while (scanf("%d", &n) && n)
    {
        int mx_val = 0, sum = 0;
        for (int i = 1; i <= n; i++)
            scanf("%d", &arr[i]), mx_val = max(mx_val, arr[i]), sum += arr[i];
        sort(arr + 1, arr + n + 1, cmp);
        for (len = mx_val; len <= sum; len++)
        {
            if (sum % len)
                continue;
            stcnt = sum / len;
            memset(vis, false, sizeof(vis));
            if (dfs(1, 0, 1))
                break;
        }
        printf("%d\n", len);
    }
    return 0;
}

First, a brief explanation of the DFS process. The DFS has three parameters: the parameter \(st\) is the number of sticks fully assembled so far, \(cab\) is the length assembled for the current stick, and \(last\) is the index of the last stick used in the previous assembly. We sort all the sticks from largest to smallest in advance, and then each DFS traversal starts from the variable \(last\); that is one place where we prune. There is another place too: if we find the answer in a later DFS, the whole search can stop. Look at the main function: the lengths are enumerated from small to large, so it must be the optimal solution. The variable \(fail\) is used to cut off the stray branches of repeated lengths. If none of the subsequent traversals yields a valid case, and this stick's length is \(0\) or \(len\), it means it can't be assembled no matter what, so we return \(false\) directly. Those are the pruning techniques for this problem.

We find that in search, we can use sorting, search-order optimization, and cutting out repeated searches to greatly speed up our programs. Pruning is a very important step.