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

ABC034-C 経路


問題へのリンク


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("4 3");
            //10
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("123 456");
            //210368064
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    const long Hou = 1000000000 + 7;

    static void Main()
    {
        List<string> InputList = GetInputList();

        long[] wkArr = InputList[0].Split(' ').Select(X => long.Parse(X)).ToArray();
        long W = wkArr[0];
        long H = wkArr[1];

        long MinVal = Math.Min(W - 1, H - 1);
        long SumVal = W - 1 + H - 1;

        long Answer = 1;
        for (long I = SumVal; SumVal - MinVal < I; I--) {
            Answer *= I;
            Answer %= Hou;
        }
        for (long I = 2; I <= MinVal; I++) {
            Answer *= DeriveGyakugen(I);
            Answer %= Hou;
        }
        Console.WriteLine(Answer);
    }

    //引数の逆元を求める
    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;
        }
    }
}


解説

フェルマーの小定理と繰り返し2乗法で、
逆元を求めてます。