AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC105-D Candy Distribution


問題へのリンク


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 2");
            WillReturn.Add("4 1 5");
            //3
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("13 17");
            WillReturn.Add("29 7 5 7 9 51 7 13 8 55 42 9 81");
            //6
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("10 400000000");
            WillReturn.Add("1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000");
            //25
        }
        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 M = wkArr[1];

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

        // mod M を設定
        for (int I = 0; I <= AArr.GetUpperBound(0); I++) {
            AArr[I] %= M;
        }

        // mod M での累積和を設定
        for (int I = 1; I <= AArr.GetUpperBound(0); I++) {
            AArr[I] += AArr[I - 1];
            AArr[I] %= M;
        }

        // mod M での累積和を集計
        var CntDict = new Dictionary<long, long>();
        for (int I = 0; I <= AArr.GetUpperBound(0); I++) {
            if (CntDict.ContainsKey(AArr[I]) == false) {
                CntDict[AArr[I]] = 0;
            }
            CntDict[AArr[I]]++;
        }

        long Answer = 0;
        foreach (var EachPair in CntDict) {
            long CurrKey = EachPair.Key;
            long CurrCnt = EachPair.Value;

            if (CurrCnt >= 2) {
                Answer += CurrCnt * (CurrCnt - 1) / 2;
            }
            if (CurrKey == 0) {
                // 始点と終点が同じ場合
                Answer += CurrCnt;
            }
        }
        Console.WriteLine(Answer);
    }
}


解説

modの累積和を求めて、
累積和が一致する始点と終点の組み合わせの数を求めてます。