标签:图论 poj 图的连通性 强连通分量 有向图的单连通性
/* ID: wuqi9395@126.com PROG: LANG: C++ */ #include<map> #include<set> #include<queue> #include<stack> #include<cmath> #include<cstdio> #include<vector> #include<string> #include<fstream> #include<cstring> #include<ctype.h> #include<iostream> #include<algorithm> using namespace std; #define INF (1<<30) #define PI acos(-1.0) #define mem(a, b) memset(a, b, sizeof(a)) #define rep(i, a, n) for (int i = a; i < n; i++) #define per(i, a, n) for (int i = n - 1; i >= a; i--) #define eps 1e-6 #define debug puts("===============") #define pb push_back #define mkp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) #define POSIN(x,y) (0 <= (x) && (x) < n && 0 <= (y) && (y) < m) typedef long long ll; typedef unsigned long long ULL; const int maxn = 1100; vector<int> g[maxn]; int dfn[maxn], low[maxn], sccno[maxn], dfs_clock, scc_cnt; stack<int> s; void dfs(int u) { dfn[u] = low[u] = ++ dfs_clock; s.push(u); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if (!dfn[v]) { dfs(v); low[u] = min(low[u], low[v]); //通过儿子更新low值 } else if (!sccno[v]) low[u] = min(low[u], dfn[v]); //通过回边更新low值(且回边访问的点必须不在已划分的强连通分量中) } if (low[u] == dfn[u]) { //得到强连通分量 scc_cnt++; while(1) { int x = s.top(); s.pop(); sccno[x] = scc_cnt; if(x == u) break; } } } void find_scc(int n) { dfs_clock = scc_cnt = 0; memset(sccno, 0, sizeof(sccno)); memset(dfn, 0, sizeof(dfn)); while(!s.empty()) s.pop(); for (int i = 1; i <= n; i++) if (!dfn[i]) dfs(i); } const int maxm = 6100; int mp[maxm][2]; vector<int> newg[maxn]; int degree[maxn]; void build_new_map(int m) { for (int i = 1; i <= scc_cnt; i++) newg[i].clear(), degree[i] = 0; for (int i = 0; i < m; i++) { int u = sccno[mp[i][0]], v = sccno[mp[i][1]]; if (u != v) { degree[v]++; newg[u].pb(v); } } } bool toposort() { queue<int> q; for (int i = 1; i <= scc_cnt; i++) if (!degree[i]) q.push(i); if (q.size() > 1) return 0; int tot = 0; while(!q.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < newg[u].size(); i++) { int v = newg[u][i]; degree[v]--; if (!degree[v]) q.push(v); } if (q.size() > 1) return 0; } return 1; } int main () { int n, m; int t; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); for (int i = 0; i <= n; i++) g[i].clear(); int u, v; rep(i, 0, m) { scanf("%d%d", mp[i], mp[i] + 1); g[mp[i][0]].pb(mp[i][1]); } find_scc(n); build_new_map(m); if (toposort()) puts("Yes"); else puts("No"); } return 0; }
POJ 2762 Going from u to v or from v to u? (有向图求单连通性)
标签:图论 poj 图的连通性 强连通分量 有向图的单连通性
原文地址:http://blog.csdn.net/sio__five/article/details/39033957