競技プログラミングの鉄則    次の問題へ    前の問題へ

A06 How Many Guests?


問題へのリンク


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("10 5");
            WillReturn.Add("8 6 9 1 2 1 10 100 1000 10000");
            WillReturn.Add("2 3");
            WillReturn.Add("1 4");
            WillReturn.Add("3 9");
            WillReturn.Add("6 8");
            WillReturn.Add("1 10");
            //15
            //24
            //1123
            //111
            //11137
        }
        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();

        var Ins_Fenwick_Tree = new Fenwick_Tree(AArr.Length);

        for (int I = 0; I <= AArr.GetUpperBound(0); I++) {
            Ins_Fenwick_Tree.Add(I, AArr[I], true);
        }

        long[] wkArr = { };
        Action<string> SplitAct = pStr =>
            wkArr = pStr.Split(' ').Select(pX => long.Parse(pX)).ToArray();

        foreach (string EachStr in InputList.Skip(2)) {
            SplitAct(EachStr);
            long L = wkArr[0] - 1;
            long R = wkArr[1] - 1;
            Console.WriteLine(Ins_Fenwick_Tree.GetSum(L, R, true));
        }
    }
}

#region Fenwick_Tree
// フェニック木
internal class Fenwick_Tree
{
    private long[] mBitArr;
    private long mN;

    // コンストラクタ
    internal Fenwick_Tree(long pItemCnt)
    {
        mN = pItemCnt;
        mBitArr = new long[pItemCnt + 1];
    }

    // [pSta,pEnd] のSumを返す
    internal long GetSum(long pSta, long pEnd, bool pIsZeroOrigin)
    {
        return GetSum(pEnd, pIsZeroOrigin) - GetSum(pSta - 1, pIsZeroOrigin);
    }

    // [0,pEnd] のSumを返す
    internal long GetSum(long pEnd, bool pIsZeroOrigin)
    {
        if (pIsZeroOrigin) {
            pEnd++; // 1オリジンに変更
        }

        long Sum = 0;
        while (pEnd >= 1) {
            Sum += mBitArr[pEnd];
            pEnd -= pEnd & -pEnd;
        }
        return Sum;
    }

    // [I] に Xを加算
    internal void Add(long pI, long pX, bool pIsZeroOrigin)
    {
        if (pIsZeroOrigin) {
            pI++; // 1オリジンに変更
        }

        while (pI <= mN) {
            mBitArr[pI] += pX;
            pI += pI & -pI;
        }
    }
}
#endregion


解説

1点加算の区間和なので
フェニック木を使ってます。