总结自《算法竞赛入门经典——训练指南》(刘汝佳),具体分析请详见书中解析。
时间戳:说白了就是记录下访问每个结点的次序。假设我们用 pre 保存,那么如果 pre[u] > pre[v], 那么就可以知道先访问的 v ,后访问的 u 。
现在给定一条边, (u, v), 且 u 的祖先为 fa, 如果有 pre[v] < pre[u] && v != fa, 那么 (u, v) 为一条反向边。
无向图的割顶和桥:
求割顶:
#include#include #include #include #include #include #include #include #include
桥:
如果v的后代只能连回 v 自己(即 low(v) > pre[u)), 只需删除(u, v)一条边就可以让图G非连通了,满足这个条件的边称为桥。换句话说,我们不仅知道结点u是割顶,还知道了(u,v)是桥。
样例:
12 12
0 1
0 4
4 8
8 9
4 9
2 3
2 7
2 6
6 7
3 7
10 7
7 11
无向图的双连通分量:
割顶的bccno无意义:割点的bccno会被多次赋值,所以它的值无意义。
调用结束后, S保证为空:
#include#include #include #include #include #include #include #include #include
样例:
5 6
0 1
0 2
1 2
2 3
2 4
3 4
有向图的强连通分量:
运行完DFS栈为什么始终为空:
换种说法, w->u->v->e, e->u, 将u, v, e 找出后,什么时候弹出的 w ? 因为 对于 w, 它的 lowlink 和 pre 相等,因此 w 作为一个 SCC, 会被弹出。
#include#include #include #include #include using namespace std;const int maxn = 2000; int pre[maxn], lowlink[maxn], sccno[maxn], dfs_clock, scc_cnt; vector<int> G[maxn]; stack<int> S;void dfs(int u){pre[u] = lowlink[u] = ++dfs_clock;S.push(u);for(int i=0; i ){int v = G[u][i];if(!pre[v]){dfs(v);lowlink[u] = min(lowlink[u], lowlink[v]);}else if(!sccno[v]){lowlink[u] = min(lowlink[u], pre[v]);}}if(lowlink[u] == pre[u]){scc_cnt++;for(;;){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(pre, 0, sizeof(pre));for(int i=0; i ){if(!pre[i]) dfs(i);} } int main(){int n, m, u, v;scanf("%d%d", &n, &m);for(int i=0; i ) G[i].clear();for(int i=0; i ){scanf("%d%d", &u, &v);G[u].push_back(v);}find_scc(n);for(int i=1; i<=scc_cnt; i++){for(int j=0; j if(sccno[j] == i) printf("%d ", j);putchar('\n');}return 0; }
样例:
12 17