题意
有 个点和 条边,第 条边从 连到 。 每条边需要指定一个方向(无向边变为有向边)。问有多少种指定方向的方案使得图中不出现环。
思路
这题不保证图联通,所以要特殊处理。
对于一个基环树,我们可以求出它的非环上的点的个数 和环上点的个数 。
每一个基环树的贡献为 。 (因为环上的边有两种方式可以使环存在,所以要减去二)。
最后答案为每一个基环树的贡献的乘积。
代码
#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;
const int N = 2e5 + 3, mod = 1e9 + 7;
int n;
int u, v;
struct P{
int id, u;
};
vector <P> e[N];
bool vis[N];
int x, y;
ll ans = 1;
int len[N];
bool b[N];
ll po(ll a, ll b){
ll ans = 1;
while(b){
if(b & 1) ans = (ans * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return ans;
}
void dfs(int u, int l){
len[u] = l + 1;
x ++;
vis[u] = 1;
for(int i = 0; i < e[u].size(); i ++){
int v = e[u][i].u;
if(b[e[u][i].id]) continue;
b[e[u][i].id] = 1;
if(vis[v]){
if(!y) y = len[u] - len[v] + 1;
}
else dfs(v, l + 1);
}
}
int main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n;
for(u = 1; u <= n; u ++){
cin >> v;
e[u].push_back({u, v});
e[v].push_back({u, u});
}
for(int i = 1; i <= n; i ++){
if(vis[i]) continue;
x = 0; y = 0;
dfs(i, 0);
x -= y;
ans = (ans * (po(2, y) - 2 + mod) % mod * po(2, x) % mod) % mod;
}
cout << ans;
return 0;
}