USACO OPEN08 Problem 'cowflix' Analysis

by Rob Kolstad

The idea on this task was to use brute force to test all 2n combinations of cows to find the heaviest combination that did not exceed the weight limit.

The easiest way to do this is to count from 1 through 2n and use the bits of an integer to indicate whether a cow is present or not. The expression (1<<n) (n ranges from 0 to, e.g., 31 or so) gives us the nth bit from the right side of a stored integer. The '&' operation uses the binary 'and' to combine the (1<<n) bit with the bit from the counter.

The program becomes very straightforward; here's my solution:

#include <stdio.h>
#include <stdlib.h>

int weight[10];

main () {
    FILE *fin = fopen ("cowflix.in", "r");
    FILE *fout = fopen ("cowflix.out", "w");
    int n, c, i, j, best, sum;

    fscanf (fin, "%d %d", &c, &n);
    for (i = 0; i < n; i++)
        fscanf (fin, "%d", &weight[i]);
    best = 0;
    for (i = 0; i < (1<<n); i++) {
        sum = 0;
        for (j = 0; j < n; j++) {
            if (i & (1<<j)) sum += weight[j];
        }
        if (sum <= c && sum > best) best = sum;
    }
    fprintf (fout, "%d\n", best);
    exit (0);
}