C♯の勉強

C♯4.0 で TopCoder の過去問を解きます。

TopCoder SRM578: WolfInZooDivTwo

public class WolfInZooDivTwo {
    struct Interval { public int left, right; }

    int N;
    Interval[] intervals;
    int?[,] memo;

    int dfs(int pos = 0, int last = -1) {
        if (pos == N) return 1;
        if (!memo[pos, last + 1].HasValue) {
            int val = dfs(pos + 1, pos);
            if (!intervals.Any(a => last < a.left && a.right <= pos)) {
                val += dfs(pos + 1, last);
            }
            memo[pos, last + 1] = val % 1000000007;
        }
        return memo[pos, last + 1].Value;
    }

    int[] ToIntArray(string[] s) {
        return String.Concat(s).Split().Select(int.Parse).ToArray();
    }

    public int count(int N, string[] L, string[] R) {
        this.N = N;
        this.intervals = ToIntArray(L)
            .Zip(ToIntArray(R), (left, right) => new Interval { left = left, right = right })
            .ToArray();

        memo = new int?[N + 1, N + 1];
        return dfs();
    }
}