强连通算法-tarjan

先贴两篇比较好的博客
https://blog.csdn.net/qq_34374664/article/details/77488976

https://blog.csdn.net/mengxiang000000/article/details/51672725

强连通分量 :有向图强连通分量:在有向图G中,如果两个顶点vi,vj间(vi>vj)有一条从vi到vj的有向路径,同时还有一条从vj到vi的有向路径,则称两个顶点强连通(strongly connected)。如果有向图G的每两个顶点都强连通,称G是一个强连通图。有向图的极大强连通子图,称为强连通分量(strongly connected components)。

直接贴模板了, 以后真正理解了在回来补。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

typedef unsigned long long ull;
typedef pair<int, int> P;
#define ms(a, b) memset((a), (b), sizeof(a))
const int N = (int)1e5 + 5;
const int INF = 0x3f3f3f3f;

inline int read() {
int res = 0;bool f = 0;char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = 1; ch = getchar(); }
while (ch <= '9' && ch >= '0') { res = (res << 3) + (res << 1) + ch - '0'; ch = getchar(); }
return f ? (~ res + 1) : res;
}

struct edge{
int u, v, ne;
}ed[N];

int head[N], dis[N], vis[N], cnt, n, m, tot;
int dfn[N], low[N];
int s[N], ind;
inline void init(){
ms(head, -1);
ms(dis, INF);
ms(vis, 0);
ind = tot = cnt = 0;
}

inline void add(int u, int v){
ed[cnt] = {u, v, head[u]};
head[u] = cnt++;
}
void tarjan(int x){
dfn[x] = low[x] = ++tot;
s[++ind] = x;
vis[x] = 1;
for (int i = head[x]; ~i; i = ed[i].ne){
int v = ed[i].v;
if (!dfn[v]){
tarjan(v); low[x] = min(low[x], low[v]);
}
else if (vis[v]){
low[x] = min(low[x], dfn[v]);
}

}
// 下面输出强连通块
if (low[x] == dfn[x]){
do {
printf("%d ", s[ind]);
vis[s[ind]] = 0;
ind--;
}while(x != s[ind + 1]);
printf("\n");
}
}

int main(){
init();
scanf("%d%d", &n, &m);
int u, v;
for (int i = 1; i <= m; ++i){
scanf("%d%d", &u, &v);
add(u, v);
}
// 避免有漏的
for (int i = 1; i <= n; ++i){
if (!dfn[i]) tarjan(i);
}
return 0;
}
1
恰似你一低头的温柔,娇弱水莲花不胜寒风的娇羞, 我的心为你悸动不休。  --mingfuyan