AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC234-F Reordering
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("aab");
//8
}
else if (InputPattern == "Input2") {
WillReturn.Add("aaa");
//3
}
else if (InputPattern == "Input3") {
WillReturn.Add("abcdefghijklmnopqrstuvwxyz");
//149621752
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
const long Hou = 998244353;
static void Main()
{
List<string> InputList = GetInputList();
string S = InputList[0];
// 度数のList
var CntList = new List<long>();
foreach (var EachItem in S.ToCharArray().GroupBy(pX => pX)) {
CntList.Add(EachItem.LongCount());
}
long UB = S.Length;
ChooseMod InsChooseMod = new ChooseMod(S.Length, Hou);
// 場合の数[文字数]なDP表
long[] DPArr = new long[UB + 1];
DPArr[0] = 1;
foreach (var EachCnt in CntList) {
for (long I = UB; 0 <= I; I--) {
if (DPArr[I] == 0) continue;
for (long J = 1; J <= EachCnt; J++) {
long PatternCnt = InsChooseMod.DeriveChoose(I + J, J);
DPArr[I + J] += DPArr[I] * PatternCnt;
DPArr[I + J] %= Hou;
}
}
}
long Answer = 0;
for (long I = 1; I <= UB; I++) {
Answer += DPArr[I];
Answer %= Hou;
}
Console.WriteLine(Answer);
}
}
#region ChooseMod
// 二項係数クラス
internal class ChooseMod
{
private long mHou;
private long[] mFacArr;
private long[] mFacInvArr;
private long[] mInvArr;
// コンストラクタ
internal ChooseMod(long pCnt, long pHou)
{
mHou = pHou;
mFacArr = new long[pCnt + 1];
mFacInvArr = new long[pCnt + 1];
mInvArr = new long[pCnt + 1];
mFacArr[0] = mFacArr[1] = 1;
mFacInvArr[0] = mFacInvArr[1] = 1;
mInvArr[1] = 1;
for (int I = 2; I <= pCnt; I++) {
mFacArr[I] = mFacArr[I - 1] * I % mHou;
mInvArr[I] = mHou - mInvArr[mHou % I] * (mHou / I) % mHou;
mFacInvArr[I] = mFacInvArr[I - 1] * mInvArr[I] % mHou;
}
}
// nCrを返す
internal long DeriveChoose(long pN, long pR)
{
if (pN < pR) return 0;
if (pN < 0 || pR < 0) return 0;
return mFacArr[pN] * (mFacInvArr[pR] * mFacInvArr[pN - pR] % mHou) % mHou;
}
}
#endregion
解説
3文字の文字列に、同じ2文字を追加するのは、
既存文字を縦棒、追加する同じ2文字を○で表せば、
○○|||
と表せるので、重複組み合わせの考え方が使えます。
このことをふまえて、DPで解いてます。
類題