AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC307-E Distinct Adjacent
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 3");
//6
}
else if (InputPattern == "Input2") {
WillReturn.Add("4 2");
//2
}
else if (InputPattern == "Input3") {
WillReturn.Add("987654 456789");
//778634319
}
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 mN = wkArr[0];
long mM = wkArr[1];
// 場合の数[先頭と同じか?]なDP表
long[] PrevDP = new long[2];
PrevDP[0] = mM * (mM - 1);
PrevDP[0] %= Hou;
for (long I = 3; I <= mN; I++) {
long[] CurrDP = new long[2];
for (long J = 0; J <= 1; J++) {
if (PrevDP[J] == 0) continue;
if (J == 0) {
CurrDP[0] += PrevDP[J] * (mM - 2);
CurrDP[0] %= Hou;
CurrDP[1] += PrevDP[J];
CurrDP[1] %= Hou;
}
if (J == 1) {
CurrDP[0] += PrevDP[J] * (mM - 1);
CurrDP[0] %= Hou;
}
}
PrevDP = CurrDP;
}
Console.WriteLine(PrevDP[0]);
}
}
解説
場合の数[先頭と同じか?]
を更新するDPで解いてます。