C♯の勉強

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

TopCoder SRM598: BinPacking

public class BinPacking {
    public int minBins(int[] item) {
        Array.Sort(item);
        int n = item.Length;
        bool[] used = new bool[n];
        int ans = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (used[i]) continue;
            int target = -1;
            for (int j = i - 1; j >= 0; j--) {
                if (used[j]) continue;
                if (item[i] + item[j] <= 300) {
                    target = j;
                    break;
                }
            }
            used[i] = true;
            if (target != -1) {
                used[target] = true;
                if (item[i] + item[target] == 200) {
                    for (int j = 0; j < n; j++) {
                        if (used[j]) continue;
                        if (item[j] == 100) {
                            used[j] = true;
                            break;
                        }
                    }
                }
            }
            ans++;
        }
        return ans;
    }
}