AtCoderのARC
次のARCの問題へ
前のARCの問題へ
ARC009-C 高橋君、24歳
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("3 2");
//3
}
else if (InputPattern == "Input2") {
WillReturn.Add("5 3");
//20
}
else if (InputPattern == "Input3") {
WillReturn.Add("4 4");
//9
}
else if (InputPattern == "Input4") {
WillReturn.Add("8 4");
//630
}
else if (InputPattern == "Input5") {
WillReturn.Add("777 77");
//1084428318
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static long[] GetSplitArr(string pStr)
{
return (pStr == "" ? new string[0] : pStr.Split(' ')).Select(pX => long.Parse(pX)).ToArray();
}
const long Hou = 1777777777;
static void Main()
{
List<string> InputList = GetInputList();
long[] wkArr = GetSplitArr(InputList[0]);
long N = wkArr[0];
long K = wkArr[1];
// 1からKまでの、要素数ごとの完全順列の個数を設定
var KanzenCntDict = new Dictionary<long, long>();
KanzenCntDict[1] = 0;
KanzenCntDict[2] = 1;
KanzenCntDict[3] = 2;
for (long I = 4; I <= K; I++) {
KanzenCntDict[I] = (I - 1) * KanzenCntDict[I - 1] + KanzenCntDict[I - 2] * (I - 1);
KanzenCntDict[I] %= Hou;
}
// nCr (mod Hou)を求める
long Answer = DeriveChoose(N, K);
Answer *= KanzenCntDict[K];
Answer %= Hou;
Console.WriteLine(Answer);
}
// nCr (mod Hou)を求める
static long DeriveChoose(long pN, long pR)
{
if (pN < pR) return 0;
pR = Math.Min(pR, pN - pR);
long WillReturn = 1;
for (long I = pN - pR + 1; I <= pN; I++) {
WillReturn *= (I % Hou);
WillReturn %= Hou;
}
for (long I = 2; I <= pR; I++) {
WillReturn *= DeriveGyakugen(I);
WillReturn %= Hou;
}
return WillReturn;
}
// 引数の逆元を求める
static Dictionary<long, long> mMemoGyakugen = new Dictionary<long, long>();
static long DeriveGyakugen(long pLong)
{
if (mMemoGyakugen.ContainsKey(pLong)) {
return mMemoGyakugen[pLong];
}
return mMemoGyakugen[pLong] = 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;
}
}
}
解説
N人からK人選択するChooseと
K人での完全順列
に対し、積の法則を使えば、解が分かります。
完全順列の漸化式のメモ
N=1のときは0通り
N=2のときは21で1通り
N=3のときは231,312で2通り
N=4のときはF(3)の4を任意の場所と入れ替えた順列
(N-1)*F(N-1)
3文字で1箇所だけ、完全順列の定義に違反した順列の違反箇所を、新たな4と入れ替えた順列
F(N-2)*(N-1)
和の法則を使い (N-1)*F(N-1) + F(N-2)*(N-1)
3文字で1箇所だけ、完全順列の定義に違反した順列の違反箇所を、新たな4と入れ替えた順列は、
具体的には
1□□
□2□
□□3
が3文字で1箇所だけ、完全順列の定義に違反した順列である。