C♯の勉強

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

TopCoder SRM 586: PiecewiseLinearFunctionDiv2

問題文

線形な区間ごとに解があるかを判定する。重解に注意。

public class PiecewiseLinearFunctionDiv2 {
    public int numberOfSolution(int[] Y, int y) {
        int n = Y.Length;
        int ans = Y[0] == y ? 1 : 0;
        for (int i = 0; i < n - 1; i++) {
            if (Y[i] < y && y <= Y[i + 1] || Y[i] > y && y >= Y[i+1]) ans++;
            if (Y[i] == Y[i + 1] && Y[i] == y) return -1;
        }
        return ans;
    }

    public int[] countSolutions(int[] Y, int[] query) {
        return query.Select(q => numberOfSolution(Y, q)).ToArray();
    }
}