典型問題    次の典型問題へ

典型アルゴリズム問題集 A 二分探索の練習問題


問題へのリンク


C#のソース

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("8 4");
            WillReturn.Add("1 3 5 7 9 11 13 15");
            //2
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("5 1000000000");
            WillReturn.Add("1 2 3 4 5");
            //-1
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
        long K = wkArr[1];

        long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();

        long Result = ExecNibunhou(K, AArr);
        Console.WriteLine(Result);
    }

    // 二分法で、K以上の値を持つ、最小の添字を返す
    static int ExecNibunhou(long pK, long[] pArr)
    {
        // 最後の要素がK未満の特殊ケース
        if (pK > pArr.Last()) {
            return -1;
        }
        // 最初の要素がK以上の特殊ケース
        if (pK <= pArr[0]) {
            return 0;
        }

        int L = 0;
        int R = pArr.GetUpperBound(0);

        while (L + 1 < R) {
            int Mid = (L + R) / 2;

            if (pArr[Mid] < pK) {
                L = Mid;
            }
            else {
                R = Mid;
            }
        }
        return R;
    }
}


解説

二分探索の基本形を使ってます。