結果
| 問題 |
No.1428 PeRmutation Question
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-01-04 09:54:17 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 47 ms / 2,000 ms |
| コード長 | 1,768 bytes |
| コンパイル時間 | 1,811 ms |
| コンパイル使用メモリ | 196,160 KB |
| 最終ジャッジ日時 | 2025-01-17 09:33:59 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 30 |
ソースコード
#include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
long long power(long long a,long long b){
long long x=1,y=a;
while(b>0){
if(b&1ll){
x=(x*y)%mod;
}
y=(y*y)%mod;
b>>=1;
}
return x%mod;
}
long long modular_inverse(long long n){
return power(n,mod-2);
}
long long factorial[524288];
long long invfact[524288];
void cfact(){
long long i;
factorial[0]=1;
factorial[1]=1;
for(i=2;i<524288;i++){
factorial[i]=factorial[i-1]*i;
factorial[i]%=mod;
}
invfact[524287]=modular_inverse(factorial[524287]);
for(i=524286;i>=0;i--){
invfact[i]=invfact[i+1]*(i+1);
invfact[i]%=mod;
}
}
struct UnionFind {
vector<int> data;
UnionFind(int size) : data(size, -1) { }
bool unionSet(int x, int y) {
x = root(x); y = root(y);
if (x != y) {
if (data[y] < data[x]) swap(x, y);
data[x] += data[y]; data[y] = x;
}
return x != y;
}
bool findSet(int x, int y) {
return root(x) == root(y);
}
int root(int x) {
return data[x] < 0 ? x : data[x] = root(data[x]);
}
int size(int x) {
return -data[root(x)];
}
};
int main(){
cfact();
int n;
cin >> n;
if(n==1){cout << "1\n";return 0;}
vector<int> a(n+1);
vector<int> mp(n+1);
UnionFind uf(n+1);
for(int i=1;i<=n;i++){
cin >> a[i];
uf.unionSet(i,a[i]);
}
for(int i=1;i<=n;i++){
if(uf.root(i)==i){mp[uf.size(i)]++;}
}
long long res=factorial[n];
if(mp[1]==n){cout << "1\n";return 0;}
int fl=1;
for(int i=1;i<=n;i++){
if(mp[i]!=0){
if(i%2==0 || mp[i]>=2){fl=0;}
res*=power((invfact[i]*factorial[i-1])%mod,mp[i]);res%=mod;
res*=invfact[mp[i]];res%=mod;
}
}
if(fl){res*=modular_inverse(2);res%=mod;}
cout << res << '\n';
return 0;
}