AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC208-E Digit Products
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("13 2");
//5
}
else if (InputPattern == "Input2") {
WillReturn.Add("100 80");
//99
}
else if (InputPattern == "Input3") {
WillReturn.Add("1000000000000000000 1000000000");
//841103275147365677
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct JyoutaiDef
{
internal long Prod; // 数字の積
internal bool FreeNum; // 数字自由フラグ
internal bool UseNonZero; // 0以外を使用したか
}
static void Main()
{
List<string> InputList = GetInputList();
long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
string StrN = wkArr[0].ToString();
long K = wkArr[1];
// 場合の数[状態定義]なDP表
var PrevDP = new Dictionary<JyoutaiDef, long>();
JyoutaiDef FirstJyoutai;
FirstJyoutai.Prod = 1;
FirstJyoutai.FreeNum = false;
FirstJyoutai.UseNonZero = 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;
long NewProd = EachPair.Key.Prod;
if (NewChar != '0' || EachPair.Key.UseNonZero) {
NewProd *= (NewChar - '0');
}
NewProd = Math.Min(NewProd, K + 1);
bool NewFreeNum = EachPair.Key.FreeNum;
if (StrN[I] > NewChar) NewFreeNum = true;
bool NewUseNonZero = EachPair.Key.UseNonZero;
if (NewChar != '0') {
NewUseNonZero = true;
}
JyoutaiDef NewJyoutai;
NewJyoutai.Prod = NewProd;
NewJyoutai.FreeNum = NewFreeNum;
NewJyoutai.UseNonZero = NewUseNonZero;
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.Prod <= K && EachPair.Key.UseNonZero)
Answer += EachPair.Value;
}
Console.WriteLine(Answer);
}
}
解説
桁DPで解いてます。