結果

問題 No.1428 PeRmutation Question
ユーザー SSRSSSRS
提出日時 2021-03-12 22:49:35
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,710 bytes
コンパイル時間 2,131 ms
コンパイル使用メモリ 174,840 KB
実行使用メモリ 5,868 KB
最終ジャッジ日時 2024-04-22 14:17:01
合計ジャッジ時間 3,610 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 WA -
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 2 ms
5,376 KB
testcase_07 AC 2 ms
5,376 KB
testcase_08 AC 2 ms
5,376 KB
testcase_09 AC 2 ms
5,376 KB
testcase_10 WA -
testcase_11 AC 2 ms
5,376 KB
testcase_12 AC 8 ms
5,376 KB
testcase_13 AC 35 ms
5,432 KB
testcase_14 AC 31 ms
5,484 KB
testcase_15 AC 22 ms
5,376 KB
testcase_16 AC 43 ms
5,820 KB
testcase_17 AC 42 ms
5,680 KB
testcase_18 AC 17 ms
5,376 KB
testcase_19 AC 12 ms
5,376 KB
testcase_20 AC 13 ms
5,376 KB
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 WA -
testcase_25 WA -
testcase_26 WA -
testcase_27 WA -
testcase_28 WA -
testcase_29 WA -
testcase_30 AC 45 ms
5,748 KB
testcase_31 WA -
testcase_32 AC 44 ms
5,748 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
long long modpow(long long a, long long b){
	long long ans = 1;
	while (b > 0){
		if (b % 2 == 1){
			ans *= a;
			ans %= MOD;
		}
		a *= a;
		a %= MOD;
		b /= 2;
	}
	return ans;
}
long long modinv(long long a){
	return modpow(a, MOD - 2);
}
vector<long long> mf = {1};
vector<long long> mfi = {1};
long long modfact(int n){
	if (mf.size() > n){
		return mf[n];
	} else {
		for (int i = mf.size(); i <= n; i++){
			long long next = mf.back() * i % MOD;
			mf.push_back(next);
			mfi.push_back(modinv(next));
		}
		return mf[n];
	}
}
long long modfactinv(int n){
	if (mfi.size() > n){
		return mfi[n];
	} else {
		return modinv(modfact(n));
	}
}
int main(){
  int N;
  cin >> N;
  vector<int> P(N);
  for (int i = 0; i < N; i++){
    cin >> P[i];
    P[i]--;
  }
  vector<int> sz;
  vector<bool> used(N, false);
  for (int i = 0; i < N; i++){
    if (!used[i]){
      int c = i;
      used[i] = true;
      sz.push_back(1);
      while (!used[P[c]]){
        c = P[c];
        used[c] = true;
        sz.back()++;
      }
    }
  }
  sort(sz.begin(), sz.end());
  int M = sz.size();
  vector<int> cnt(N + 1, 0);
  for (int i = 0; i < M; i++){
    cnt[sz[i]]++;
  }
  int sum = 0;
  long long ans = modfact(N);
  for (int i = 0; i < M; i++){
    ans *= modinv(sz[i]);
    ans %= MOD;
  }
  for (int i = 1; i <= N; i++){
    ans *= modfactinv(cnt[i]);
    ans %= MOD;
  }
  if (N % 2 == 1 && N >= 3){
    if (sz.size() == 1){
      ans *= modinv(2);
      ans %= MOD;
    }
  }
  if (N % 2 == 0){
    if (sz.size() == 2){
      if (sz[0] == 1){
        ans *= modinv(2);
        ans %= MOD;
      }
    }
  }
  cout << ans << endl;
}
0