AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC154-E Almost Everywhere Zero
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("100");
WillReturn.Add("1");
//19
}
else if (InputPattern == "Input2") {
WillReturn.Add("25");
WillReturn.Add("2");
//14
}
else if (InputPattern == "Input3") {
WillReturn.Add("314159");
WillReturn.Add("2");
//937
}
else if (InputPattern == "Input4") {
WillReturn.Add("9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
WillReturn.Add("3");
//117879300
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct JyoutaiDef
{
internal bool FreeNum; // 数字自由フラグ
internal long NonZeroCnt; // ゼロ以外数字の数
}
static void Main()
{
List<string> InputList = GetInputList();
string StrN = InputList[0];
long K = long.Parse(InputList[1]);
// 場合の数[状態定義]なDP表
var PrevDP = new Dictionary<JyoutaiDef, long>();
JyoutaiDef FirstJyoutai;
FirstJyoutai.NonZeroCnt = 0;
FirstJyoutai.FreeNum = false;
PrevDP[FirstJyoutai] = 1;
for (int I = 0; I <= StrN.Length - 1; I++) {
var CurrDP = new Dictionary<JyoutaiDef, long>();
foreach (var EachPair in PrevDP) {
for (char NewChar = '0'; NewChar <= '9'; NewChar++) {
if (EachPair.Key.FreeNum == false && StrN[I] < NewChar) break;
bool NewFreeNum = EachPair.Key.FreeNum;
if (StrN[I] > NewChar) NewFreeNum = true;
long NewNonZeroCnt = EachPair.Key.NonZeroCnt;
if (NewChar != '0') {
NewNonZeroCnt++;
}
// 枝切り
if (NewNonZeroCnt > K) continue;
JyoutaiDef NewJyoutai;
NewJyoutai.NonZeroCnt = NewNonZeroCnt;
NewJyoutai.FreeNum = NewFreeNum;
if (CurrDP.ContainsKey(NewJyoutai) == false) {
CurrDP[NewJyoutai] = 0;
}
CurrDP[NewJyoutai] += EachPair.Value;
}
}
PrevDP = CurrDP;
}
long Answer = 0;
foreach (var EachPair in PrevDP) {
if (EachPair.Key.NonZeroCnt == K) {
Answer += EachPair.Value;
}
}
Console.WriteLine(Answer);
}
}
解説
桁DPで解いてます。