CodeForces 711D Directed Roads (DFS判环+计数)
Posted dwtfukgv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces 711D Directed Roads (DFS判环+计数)相关的知识,希望对你有一定的参考价值。
题意:给定一个有向图,然后你可能改变某一些边的方向,然后就形成一种新图,让你求最多有多少种无环图。
析:假设这个图中没有环,那么有多少种呢?也就是说每一边都有两种放法,一共有2^x种,x是边数,那么如果有环呢?假设x是这个连通块的边数,
y是这个环的边数,那么就一共有2^x * (2 ^ y - 2) 种,减去这两种就是一边也不变,和所有的边都就变,这样就形成环了。
那么怎么计算呢?这个题的边很特殊,所以我们可以利用这个特征,我们在每个连通块时,用vis记录一下开始的父结点,用cnt记录每一个到每个点的深度,
然后如果产生环了,那么我们就可以很轻松的算出这个环的结点数,用当前的cnt减去就好,然后用sum记录一下环结点的总数,
最后用n减去环中的结点数,就剩下不是环的结点数了。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <list> #include <sstream> #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const LL LNF = 0x3f3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 2e5 + 5; const int mod = 1e9 + 7; const int dr[] = {-1, 1, 0, 0, 1, 1, -1, -1}; const int dc[] = {0, 0, 1, -1, 1, -1, 1, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline int Min(int a, int b){ return a < b ? a : b; } inline int Max(int a, int b){ return a > b ? a : b; } inline LL Min(LL a, LL b){ return a < b ? a : b; } inline LL Max(LL a, LL b){ return a > b ? a : b; } inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int vis[maxn]; int a[maxn], cnt[maxn]; LL ans; int sum; LL quick_pow(LL a, LL b){ LL ans = 1; while(b){ if(b & 1) ans = (ans * a) % mod; b >>= 1; a = (a * a) % mod; } return ans; } void dfs(int d, int u, int fa){ vis[u] = fa; cnt[u] = d; if(!vis[a[u]]) dfs(d+1, a[u], fa); else if(vis[a[u]] == fa){ sum += cnt[u]-cnt[a[u]]+1; ans = (ans * (quick_pow(2LL, cnt[u]-cnt[a[u]]+1) - 2 + mod)) % mod; } } int main(){ while(scanf("%d", &n) == 1){ memset(vis, 0, sizeof vis); memset(cnt, 0, sizeof cnt); for(int i = 1; i <= n; ++i) scanf("%d", &a[i]); ans = 1, sum = 0; for(int i = 1; i <= n; ++i){ if(vis[i]) continue; dfs(0, i, i); } ans = (ans * quick_pow(2LL, n-sum)) % mod; cout << ans << endl; } return 0; }
以上是关于CodeForces 711D Directed Roads (DFS判环+计数)的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces 711 D. Directed Roads (DFS判环)
Codeforces Round #550 (Div. 3) F. Graph Without Long Directed Paths
Codeforces Round #550 (Div. 3) F. Graph Without Long Directed Paths
Codeforces Round #369 (Div. 2)-D Directed Roads
Codeforces 1144F Graph Without Long Directed Paths (DFS染色+构造)