AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC021-D 多重ループ


問題へのリンク


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("10");
            WillReturn.Add("2");
            //55
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("10");
            WillReturn.Add("3");
            //220
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("10");
            WillReturn.Add("4");
            //715
        }
        else if (InputPattern == "Input4") {
            WillReturn.Add("400");
            WillReturn.Add("296");
            //546898535
        }
        else if (InputPattern == "Input5") {
            WillReturn.Add("100000");
            WillReturn.Add("100000");
            //939733670
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    const long Hou = 1000000007;

    static void Main()
    {
        List<string> InputList = GetInputList();
        long N = long.Parse(InputList[0]);
        long K = long.Parse(InputList[1]);

        Console.WriteLine(DeriveChoose(N - 1 + K, K));
    }

    // nCr (mod Hou)を求める
    static long DeriveChoose(long pN, long pR)
    {
        pR = Math.Min(pR, pN - pR);

        long WillReturn = 1;
        for (long I = pN - pR + 1; I <= pN; I++) {
            WillReturn *= I;
            WillReturn %= Hou;
        }
        for (long I = 2; I <= pR; I++) {
            WillReturn *= DeriveGyakugen(I);
            WillReturn %= Hou;
        }
        return WillReturn;
    }

    // 引数の逆元を求める
    static long DeriveGyakugen(long pLong)
    {
        return DeriveBekijyou(pLong, Hou - 2, Hou);
    }

    // 繰り返し2乗法で、(NのP乗) Mod Mを求める
    static long DeriveBekijyou(long pN, long pP, long pM)
    {
        long CurrJyousuu = pN % pM;
        long CurrShisuu = 1;
        long WillReturn = 1;

        while (true) {
            // 対象ビットが立っている場合
            if ((pP & CurrShisuu) > 0) {
                WillReturn = (WillReturn * CurrJyousuu) % pM;
            }

            CurrShisuu *= 2;
            if (CurrShisuu > pP) return WillReturn;
            CurrJyousuu = (CurrJyousuu * CurrJyousuu) % pM;
        }
    }
}


解説

1 <= A <= B <= 10 を満たす
A,Bの場合の数は、
インクリメントが9回、表示が2回の、重複組み合わせで
11C2 で求まり、

1 <= A <= B <= C <= 10 を満たす
A,B,Cの場合の数は、
インクリメントが9回、表示が3回の、重複組み合わせで
12C2 で求まります。