题目大意:给定一个 N 个点,N 条边的无向图,现给每条边定向,求有多少种定向方式使得定向后的有向图中无环。
题解:显然,这是一个外向树森林,定向后存在环的情况只能发生在基环树中环的位置,环分成顺时针和逆时针两种情况,其他边方向随意。因此,记外向树森林中环的大小为 \(w[i]\),则答案为\[2^{n-\sum w[i]}*\prod (2^{w[i]}-2)\]
代码如下
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
const int mod=1e9+7;
inline int read(){
int x=0,f=1;char ch;
do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
return f*x;
}
struct node{
int nxt,to;
}e[maxn<<1];
int tot=1,head[maxn];
inline void add_edge(int from,int to){
e[++tot]=node{head[from],to},head[from]=tot;
}
int n,stk[maxn],top,p[maxn],dep[maxn];
int vis[maxn];// int not bool
void dfs(int u,int d){
vis[u]=1,dep[u]=d;
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to;
if(!vis[v])dfs(v,d+1);
else if(vis[v]==1)stk[++top]=dep[u]-dep[v]+1;
}
vis[u]=2;
}
inline int mul(int x,int y){return (long long)x*y%mod;}
void read_and_parse(){
n=read(),p[0]=1;
for(int i=1;i<=n;i++)p[i]=mul(2,p[i-1]);
for(int i=1,to;i<=n;i++)to=read(),add_edge(i,to);
}
void solve(){
for(int i=1;i<=n;i++)if(!vis[i])dfs(i,1);
int sum=0,res=1;
for(int i=1;i<=top;i++){
sum+=stk[i];
res=mul(res,p[stk[i]]-2);
}
printf("%d\n",mul(p[n-sum],res));
}
int main(){
read_and_parse();
solve();
return 0;
}