这里需要判断图中每个环具有的边数目,对于每个环,如果有s条边,那么这个环的变换方式有2^s-2种,而对于不在环上的边,换与不换都可以。
判断图中每个环具有的边数目的方法详见代码,至于为什么这样,可以画一画图或者看看cf上数据画一画就会懂了.
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
const int maxn=200000+100;
int a[maxn],vis[maxn];
ll get(int num)
{
ll ans=1,p=2;
while(num)
{
if(num&1)
ans=(ans*p)%mod;
p=(p*p)%mod;
num/=2;
}
return ans;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
ll ans=1;
memset(vis,0,sizeof(vis));
int cnt=0;
int nn=n;
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
int x=i;
int now=cnt;
while(!vis[x])
{
vis[x]=++cnt;
x=a[x];
}
if(vis[x]>now)
{
int num=cnt-vis[x]+1;
ans=(ans*(get(num)-2+mod))%mod;
nn-=num;
}
}
}
ans=(ans*get(nn))%mod;
printf("%I64d\n",ans);
}