C♯の勉強

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

TopCoder SRM600: ORSolitaireDiv2

Div1Easy の ORSolitaire とは違って、|numbers| <= 20 のため、全探索でも通る

public class ORSolitaireDiv2 {
    public int getMinimum(int[] numbers, int goal) {
        int n = numbers.Length;
        int ans = int.MaxValue;
        for (int i = 0; i < (1 << n); i++) {
            int or = 0, cnt = 0;
            for (int j = 0; j < n; j++) {
                if (((1 << j) & i) != 0) {
                    cnt++;
                    if ((goal | numbers[j]) != goal) continue;
                    or |= numbers[j];
                }
            }
            if (or != goal)
                ans = Math.Min(ans, n - cnt);
        }
        return ans;
    }
}