首先套路地,看到 首先考虑 连边,建立内向基环树。
然后我们先考虑对于一棵树如何计算贡献。
我们发现一个点如果操作过,那么他一定在他的目标位置,如果没操作过,那么他有可能停在原地,也有可能往他入边的某个方向跑过去。
那么对于树的方案数就有
考虑基环树的方案如何统计。我们会发现一个点,就是说环上的边不能全部选。
考虑容斥,总的 ,然后我们发现你全部边都被选,实际上和环上的边少选一条边是等价的,所以说我们要把多算的少选一条边的情况减掉。
要减去 ,然后这题就做完了,时间复杂度
启示:
对于 有关系的,可以考虑 连边,建基环树
#include<bits/stdc++.h>
typedef long long LL;
using namespace std;
const int MAXN=1e6+10,P=1e9+7;
int n;
vector<int> e[MAXN];
void add(int f,int t) {
e[f].push_back(t);
}
vector<int> ls;
int du[MAXN],tot;
bool vis[MAXN],sf[MAXN];
LL fad(LL x,LL y) {
return (x+y>=P?x+y-P:x+y);
}
void dfs(int u) {
vis[u]=1; ls.push_back(u);
for(auto t:e[u]) {
if(!vis[t]) dfs(t);
}
}
int cir[MAXN],a[MAXN];
LL solve(int u) {
tot=0; ls.clear();
dfs(u);
while(!sf[u]) {
sf[u]=1;
u=a[u];
}
int v=a[u]; cir[++tot]=u;
while(v!=u) {
cir[++tot]=v;
v=a[v];
}
for(auto t:ls) sf[t]=0;
LL s1=1,s2=0;
for(int i=1;i<=tot;++i) {
sf[cir[i]]=1;
s1=s1*(du[cir[i]]+1)%P;
s2=fad(s2,du[cir[i]]);
}
s1=fad(s1,P-s2);
for(auto t:ls) {
if(!sf[t]) {
s1=s1*(du[t]+1)%P;
}
}
return s1;
}
void vmain() {
scanf("%d",&n);
for(int i=1;i<=n;++i) du[i]=vis[i]=sf[i]=0,e[i].clear();
for(int i=1;i<=n;++i) {
scanf("%d",&a[i]);
add(i,a[i]); add(a[i],i); ++du[a[i]];
}
LL ans=1;
for(int i=1;i<=n;++i) {
if(!vis[i]) {
ans=ans*solve(i)%P;
}
}
printf("%lld\n",ans);
}
int main () {
int T=1;
// scanf("%d",&T);
while(T--) vmain();
return 0;
}