典型90問    次の典型90問へ

典型90問 001 Yokan Party(★4)


問題へのリンク


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("3 34");
            WillReturn.Add("1");
            WillReturn.Add("8 13 26");
            //13
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("7 45");
            WillReturn.Add("2");
            WillReturn.Add("7 11 16 20 28 34 38");
            //12
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("3 100");
            WillReturn.Add("1");
            WillReturn.Add("28 54 81");
            //46
        }
        else if (InputPattern == "Input4") {
            WillReturn.Add("3 100");
            WillReturn.Add("2");
            WillReturn.Add("28 54 81");
            //26
        }
        else if (InputPattern == "Input5") {
            WillReturn.Add("20 1000");
            WillReturn.Add("4");
            WillReturn.Add("51 69 102 127 233 295 350 388 417 466 469 523 553 587 720 739 801 855 926 954");
            //170
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static long mL;
    static long mK;
    static List<long> mLenList = new List<long>();

    static void Main()
    {
        List<string> InputList = GetInputList();

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

        mK = long.Parse(InputList[1]);

        long[] AArr = InputList[2].Split(' ').Select(pX => long.Parse(pX)).ToArray();
        var RunSumList = new List<long>();
        RunSumList.AddRange(AArr);
        RunSumList.Add(mL);

        mLenList.Add(RunSumList[0]);

        for (int I = 1; I <= RunSumList.Count - 1; I++) {
            mLenList.Add(RunSumList[I] - RunSumList[I - 1]);
        }

        long L = 0;
        long R = mL + 1;

        while (L + 1 < R) {
            long Mid = (L + R) / 2;
            if (CanAchieve(Mid)) {
                L = Mid;
            }
            else {
                R = Mid;
            }
        }
        Console.WriteLine(L);
    }

    // 全てNeedSum以上にできるかを返す
    static bool CanAchieve(long pNeedSum)
    {
        var ValList = new List<long>();

        long SumVal = 0;
        int UB = mLenList.Count - 1;
        foreach (int EachLen in mLenList) {
            SumVal += EachLen;
            if (SumVal >= pNeedSum) {
                ValList.Add(SumVal);
                SumVal = 0;
            }
        }

        if (ValList.Count(pX => pX >= pNeedSum) >= mK + 1) {
            return true;
        }
        return false;
    }
}


解説

答えを二分探索してます。