这题和我上一篇博客有着惊人的相似..
同样的陈述,只是每个指向变成了有向的,问你选择一些边来翻转,如果翻转之后不存在环,那就是可行的,这种可行方式有多少种.
我们反向考虑,翻转后会存在环的方式有多少种,按照上一篇博客的方法,进行剥离,这里不存在”完美树”只有2,3.这里,因为有向环的定义,2也被认定为一种特殊的环.
这题在组合上的计算是容易的.
发现了这个图的性质,按照之前做法即可.
#include <iostream>
#include <set>
#include <vector>
using namespace std;
#define debug(x) std::cerr << #x << " = " << (x) << std::endl
typedef long long LL;
const int MAXN = 2e5+17;
const int MOD = 1e9+7;
int a[MAXN],ind[MAXN],vis[MAXN];
vector<int > G[MAXN];
LL qm(LL a,LL b)
{
LL res = 1;
while(b)
{
if(b&1) res = res*a%MOD;
a = a*a%MOD;
b>>=1;
}
return res;
}
vector<int > dap;
void dfs(int u)
{
dap.push_back(u);
vis[u]=1;
for(auto i : G[u])
if(!vis[i])
dfs(i);
}
int main(int argc ,char const *argv[])
{
#ifdef noob
freopen("Input.txt","r",stdin);freopen("Output.txt","w",stdout);
#endif
int n;
cin>>n;
for (int i = 0; i < n; ++i)
{
cin>>a[i];
a[i]--;
ind[i]++,ind[a[i]]++;
G[i].push_back(a[i]);
G[a[i]].push_back(i);
}
LL ans = 1;
for (int i = 0; i < n; ++i)
{
if(!vis[i])
{
dap.clear();
dfs(i);
set<pair<int,int > > s;
for(auto i : dap)
s.insert({ind[i],i});
bool have = false;
for(auto i : dap)
{
if(a[a[i]]==i)
{
ans = (ans*qm(2, dap.size()-1))%MOD;
have = true;
break;
}
}
while(1&&!have)
{
pair<int,int > now = *s.begin();
if(now.first!=1) break;
s.erase(s.begin());
for (auto i: G[now.second])
{
if(s.find({ind[i],i})!=s.end()) s.erase(s.find({ind[i],i}));
ind[i]--;
if(ind[i])
s.insert({ind[i],i});
}
}
if(!have) ans = (ans*(qm(2, dap.size())-(2LL*(qm(2LL,dap.size()-s.size())))%MOD))%MOD;
}
}
cout<<(ans%MOD+MOD)%MOD<<endl;
return 0;
}