Codeforces Round #369 Div. 2 D

基环树

有可能是基环树,也有可能不是,不过只需要多dfs几次,把所有环扣出来就好了。

环内的边定向方式是2^n - 2,n是环的大小,环外的边随便定向

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
#define FAST_IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int X = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}
const int N = 300005;
const int MOD = 1e9 + 7;
int n, cnt, head[N], dfn[N], k, fa[N];
struct Edge { int v, next; } edge[N<<1];
vector<int> loop;

void addEdge(int a, int b){
    edge[cnt].v = b, edge[cnt].next = head[a], head[a] = cnt ++;
}

void dfs(int s){
    dfn[s] = ++k;
    for(int i = head[s]; i != -1; i = edge[i].next){
        int u = edge[i].v;
        if(u == fa[s]) continue;
        if(dfn[u]){
            if(dfn[u] < dfn[s]) continue;
            loop.push_back(u);
            for(; u != s; u = fa[u]) loop.push_back(fa[u]);
        }
        else fa[u] = s, dfs(u);
    }
}

int main(){

    full(head, -1);
    n = read();
    for(int i = 1; i <= n; i ++){
        int v = read();
        addEdge(i, v), addEdge(v, i);
    }
    ll ans = 1;
    int num = 0;
    for(int i = 1; i <= n; i ++){
        if(!dfn[i]){
            dfs(i);
            int m = (int) loop.size();
            ans = 1LL * (fpow(2, m, MOD) - 2) * ans % MOD;
            num += m;
            loop.clear();
        }
    }
    ans = ans * fpow(2, n - num, MOD) % MOD;
    printf("%lld
", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/onionQAQ/p/10975164.html