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

ABC323-E Playlist


問題へのリンク


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 6");
            WillReturn.Add("3 5 6");
            //369720131
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("5 0");
            WillReturn.Add("1 2 1 2 1");
            //598946612
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("5 10000");
            WillReturn.Add("1 2 3 4 5");
            //586965467
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    const long Hou = 998244353;

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

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

        long Gyakugen = DeriveGyakugen(TArr.Length);

        // 確率[現在時刻]なDP表
        long[] DPArr = new long[X + 1];
        DPArr[0] = 1;

        long Answer = 0;

        for (long I = 0; I <= X; I++) {
            if (DPArr[I] == 0) continue;

            for (long J = 0; J <= TArr.GetUpperBound(0); J++) {
                long NewX = I + TArr[J];
                long NewProb = DPArr[I] * Gyakugen;

                if (NewX > X) {
                    if (J == 0) {
                        Answer += NewProb;
                        Answer %= Hou;
                    }
                }
                else {
                    DPArr[NewX] += NewProb;
                    DPArr[NewX] %= Hou;
                }
            }
        }
        Console.WriteLine(Answer);
    }

    // 引数の逆元を求める
    static Dictionary<long, long> mMemoGyakugen = new Dictionary<long, long>();
    static long DeriveGyakugen(long pLong)
    {
        if (mMemoGyakugen.ContainsKey(pLong)) {
            return mMemoGyakugen[pLong];
        }
        return mMemoGyakugen[pLong] = DeriveBekijyou(pLong, Hou - 2, Hou);
    }

    // 繰り返し2乗法で、(NのP乗) Mod Mを求める
    static long DeriveBekijyou(long pN, long pP, long pM)
    {
        long CurrJyousuu = pN % pM;
        long CurrShisuu = 1;
        long WillReturn = 1;

        while (true) {
            // 対象ビットが立っている場合
            if ((pP & CurrShisuu) > 0) {
                WillReturn = (WillReturn * CurrJyousuu) % pM;
            }

            CurrShisuu *= 2;
            if (CurrShisuu > pP) return WillReturn;
            CurrJyousuu = (CurrJyousuu * CurrJyousuu) % pM;
        }
    }
}


解説

確率[現在時刻]で確率DPしてます。