典型90問
次の典型90問へ
前の典型90問へ
典型90問 069 Colorful Blocks 2(★3)
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("2 3");
//6
}
else if (InputPattern == "Input2") {
WillReturn.Add("10 2");
//0
}
else if (InputPattern == "Input3") {
WillReturn.Add("2021 617");
//53731843
}
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[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
long N = wkArr[0];
long K = wkArr[1];
long Answer = 1;
if (N == 1) {
Answer *= K;
Answer %= Hou;
Console.WriteLine(Answer);
return;
}
if (N == 2) {
Answer *= K;
Answer %= Hou;
Answer *= K - 1;
Answer %= Hou;
Console.WriteLine(Answer);
return;
}
Answer *= K;
Answer %= Hou;
Answer *= K - 1;
Answer %= Hou;
Answer *= K - 2;
Answer %= Hou;
long RestN = N - 3;
if (RestN >= 1) {
Answer *= DeriveBekijyou(K - 2, RestN, Hou);
Answer %= Hou;
}
Console.WriteLine(Answer);
}
// 繰り返し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;
}
}
}
解説
設置する個数で場合分けしてます。