USACO FEB09 Problem 'bullcow' Analysis

by Neal Wu

The solution to this problem uses a technique called dynamic programming, also known as DP. Let fn be the number of ways we can have a sequence of n animals so that no two bulls have fewer than K cows between them. We first note that f0 = 1. We then try to find a recurrence to compute fn in general by considering two cases for the first animal in the sequence:

Thus, combining our two cases together, we have the recurrence fn = fn - 1 + fn - K - 1. This gives us a simple solution:

#include <cstdio>
using namespace std;

FILE *fin = fopen ("bullcow.in", "r"), *fout = fopen ("bullcow.out", "w");

const int MAXN = 100005, MOD = 5000011;

int N, K, dp [MAXN];

int main ()
{
    fscanf (fin, "%d %d", &N, &K);

    for (int n = 0; n <= N; n++)
        if (n <= K)
            dp [n] = n + 1;
        else
            dp [n] = (dp [n - 1] + dp [n - K - 1]) % MOD;

    fprintf (fout, "%d\n", dp [N]);

    return 0;
}