AOJ本の読書メモ   AOJ    次のAOJの問題へ    前のAOJの問題へ

DSL_3_C: The Number of Windows


問題へのリンク


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("6 5");
            WillReturn.Add("1 2 3 4 5 6");
            WillReturn.Add("6 9 12 21 15");
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

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

        long UB = AArr.GetUpperBound(0);
        long[] RunSumArr = (long[])AArr.Clone();
        for (long I = 1; I <= UB; I++) {
            RunSumArr[I] += RunSumArr[I - 1];
        }

        foreach (long EachSumLimit in QArr) {
            long Answer = 0;

            for (long I = 0; I <= UB; I++) {
                long CurrVal = AArr[I];
                if (CurrVal > EachSumLimit) continue;

                long PrevRunSum = 0;
                if (I > 0) PrevRunSum = RunSumArr[I - 1];

                long SearchVal = EachSumLimit + PrevRunSum;

                int ResultInd = ExecNibunhou_LowerOrEqual_Max(SearchVal, RunSumArr);
                if (ResultInd == -1) continue;
                if (ResultInd < I) continue;
                Answer += ResultInd - I + 1;
            }
            Console.WriteLine(Answer);
        }
    }

    // 二分法で、Val以下で最大の値を持つ、添字を返す
    static int ExecNibunhou_LowerOrEqual_Max(long pVal, long[] pArr)
    {
        if (pArr.Length == 0) return -1;

        // 最後の要素がVal以下の特殊ケース
        if (pVal >= pArr.Last()) {
            return pArr.GetUpperBound(0);
        }
        // 最初の要素がVal超えの特殊ケース
        if (pVal < pArr[0]) {
            return -1;
        }

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

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

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

}


解説

負数がないので、累積和は単調増加です。
なので、区間の左端を全探索し、右端を二分探索してます。