DPコンテスト    次のDPコンテストの問題へ    前のDPコンテストの問題へ

Educational DP Contest S Digit Sum


問題へのリンク


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("30");
            WillReturn.Add("4");
            //6
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("1000000009");
            WillReturn.Add("1");
            //2
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("98765432109876543210");
            WillReturn.Add("58");
            //635270834
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    const int Hou = 1000000007;

    static void Main()
    {
        List<string> InputList = GetInputList();
        string StrN = InputList[0];
        int D = int.Parse(InputList[1]);

        // 場合の数[Dを法とした余り,数字自由フラグ]なDP表
        int[,] PrevDP = new int[D, 2];
        PrevDP[0, 0] = 1;

        for (int I = 0; I <= StrN.Length - 1; I++) {
            int[,] CurrDP = new int[D, 2];

            for (int J = 0; J <= PrevDP.GetUpperBound(0); J++) {
                for (int K = 0; K <= 1; K++) {
                    if (PrevDP[J, K] == 0) continue;

                    for (char NewChar = '0'; NewChar <= '9'; NewChar++) {
                        if (K == 0 && StrN[I] < NewChar) break;

                        int NewJ = (J + NewChar - '0') % D;

                        int NewK = K;
                        if (StrN[I] > NewChar) NewK = 1;

                        CurrDP[NewJ, NewK] += PrevDP[J, K];
                        CurrDP[NewJ, NewK] %= Hou;
                    }
                }
            }
            PrevDP = CurrDP;
        }

        int Answer = 0;
        Answer += PrevDP[0, 0]; Answer %= Hou;
        Answer += PrevDP[0, 1]; Answer %= Hou;

        Answer--; // 0の分を引く
        if (Answer < 0) Answer += Hou;
        Console.WriteLine(Answer);
    }
}


解説

桁DPで解いてます。