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

ABC280-E Critical Hit


問題へのリンク


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 10");
            //229596204
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("5 100");
            //3
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("280 59");
            //567484387
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    const long Hou = 998244353;

    static long mP;

    static void Main()
    {
        List<string> InputList = GetInputList();
        long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
        long N = wkArr[0];
        mP = wkArr[1];
        long Result = DFS(N);
        Console.WriteLine(Result);
    }

    static Dictionary<long, long> mMemo = new Dictionary<long, long>();
    static long DFS(long pRestHP)
    {
        if (pRestHP <= 0) return 0;

        if (mMemo.ContainsKey(pRestHP)) {
            return mMemo[pRestHP];
        }

        long wkBunsuu = mP * DeriveGyakugen(100);
        wkBunsuu %= Hou;

        long Ex1 = DFS(pRestHP - 2) * wkBunsuu;
        long Ex2 = DFS(pRestHP - 1) * (1 - (wkBunsuu));
        Ex1 %= Hou;
        Ex2 %= Hou;

        long ExSum = Ex1 + Ex2;
        ExSum %= Hou;

        if (ExSum < 0) ExSum += Hou;

        return mMemo[pRestHP] = 1 + ExSum;
    }

    // 引数の逆元を求める
    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;
        }
    }
}


解説

メモ化再帰で解いてます。