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

ABC275-E Sugoroku 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("2 2 1");
            //499122177
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("10 5 6");
            //184124175
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("100 1 99");
            //0
        }
        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 UB = wkArr[0];
        long M = wkArr[1];
        long TryCnt = wkArr[2];

        // 確率[現在位置]なDP表
        long[] PrevDP = new long[UB + 1];
        PrevDP[0] = 1;

        long Answer = 0;
        long CachedGyakugen = DeriveGyakugen(M);
        for (long I = 1; I <= TryCnt; I++) {
            long[] CurrDP = new long[UB + 1];
            for (long J = 0; J <= UB; J++) {
                if (PrevDP[J] == 0) continue;

                for (long K = 1; K <= M; K++) {
                    long NewJ = J + K;
                    if (NewJ > UB) {
                        long Diff = Math.Abs(UB - NewJ);
                        NewJ = UB - Diff;
                    }
                    CurrDP[NewJ] += PrevDP[J] * CachedGyakugen;
                    CurrDP[NewJ] %= Hou;
                }
                Answer += CurrDP[UB];
                Answer %= Hou;
                CurrDP[UB] = 0;
            }
            PrevDP = CurrDP;
        }
        Console.WriteLine(Answer);
    }

    // 引数の逆元を求める
    static long DeriveGyakugen(long pLong)
    {
        return 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してます。

ゴールに到達したら、解に計上して、
次の試行で、配らないようにしてます。