AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC360-E Random Swaps of Balls
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 1");
//499122178
}
else if (InputPattern == "Input2") {
WillReturn.Add("3 2");
//554580198
}
else if (InputPattern == "Input3") {
WillReturn.Add("4 4");
//592707587
}
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 MasuCnt = wkArr[0];
long TryCnt = wkArr[1];
if (MasuCnt == 1) {
Console.WriteLine(1);
return;
}
// 確率[1番左に黒玉があるか?]
long[] PrevDP = new long[2];
PrevDP[1] = 1;
long AllPatternCnt = MasuCnt * MasuCnt;
AllPatternCnt %= Hou;
for (long I = 1; I <= TryCnt; I++) {
long[] CurrDP = new long[2];
for (long J = 0; J <= 1; J++) {
if (PrevDP[J] == 0) continue;
if (J == 0) {
long ChangeProb = 2 * DeriveGyakugen(AllPatternCnt);
ChangeProb %= Hou;
CurrDP[1] += PrevDP[J] * ChangeProb;
CurrDP[1] %= Hou;
CurrDP[0] += PrevDP[J] * (1 - ChangeProb);
CurrDP[0] %= Hou;
if (CurrDP[0] < 0) {
CurrDP[0] += Hou;
}
}
if (J == 1) {
long ChangeProb = 2 * (MasuCnt - 1);
ChangeProb %= Hou;
ChangeProb *= DeriveGyakugen(AllPatternCnt);
ChangeProb %= Hou;
CurrDP[0] += PrevDP[J] * ChangeProb;
CurrDP[0] %= Hou;
CurrDP[1] += PrevDP[J] * (1 - ChangeProb);
CurrDP[1] %= Hou;
if (CurrDP[1] < 0) {
CurrDP[1] += Hou;
}
}
}
PrevDP = CurrDP;
}
long Answer = 0;
Answer += PrevDP[1];
long SuuretuSum = MasuCnt * (MasuCnt + 1);
SuuretuSum %= Hou;
SuuretuSum *= DeriveGyakugen(2);
SuuretuSum %= Hou;
SuuretuSum--;
if (SuuretuSum < 0) SuuretuSum += Hou;
SuuretuSum *= DeriveGyakugen(MasuCnt - 1);
SuuretuSum %= Hou;
Answer += PrevDP[0] * SuuretuSum;
Answer %= 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;
}
}
}
解説
確率[1番左に黒玉があるか?]
で確率DPし、最後に期待値を求めてます。