「学习笔记」Tarjan
Soul_direction
·
·
算法·理论
:::warning[Tip]{open}
\small{请复制\ Markdown\ 到洛谷以获取最佳阅读体验}
:::
\LARGE\text{Part0\ 目录}
-
\normalsize\text{Part0\ }\small{目录}
-
\normalsize\text{Part1}\cdot \small{有向图的强连通分量}
\small\color{White}{Part\ 1\ 有向图的强连通分量}
\LARGE\text{Part1}\cdot\ $ $\texttt{有向图的强连通分量}
定义
对于有向图 G\in(V,E),有 2 点 u,v\in G,满足 u\rightsquigarrow v 且 v\rightsquigarrow u,则称 u,v 强连通。若 G 满足任意 2 点强连通,则称 G 为强连通图,一张图的强连通分量为其极大强连通子图。
前置
$low_u$:回溯值,即 $u$ 在图中可访问到的最早时间戳。
看一个例子:

如图,以 $1$ 节点作为搜索起始点。
则 $dfn_1$ 为 $1$,$low_4$ 为 $1$。
#### 实现
例题:[P2863 [USACO06JAN] The Cow Prom S](https://www.luogu.com.cn/problem/P2863)
- 对于 dfs 到的点 $u$,更新 $dfn_u$ 与 $low_u$,并将 $u$ 入栈,由于图不一定连通,所以标记访问数组 $used_u$ 以便主函数跑 tarjan。
:::info[Code]{open}
```cpp
dfn[u]=low[u]=++tsp;
//tsp为全局时间戳变量
sto.push(u);
stag[u]=used[u]=1;
```
:::
- 接着开始跳边遍历,记邻点为 $v$。
对于 $v$,有如下可能:
1. $v$ 未被访问,即未更新 $dfn_v$,则对其搜索。由于该情况下 $v$ 为 $u$ 的子节点,故用其 $low_v$ 更新当前节点 $low_u$。
2. $v$ 已被访问且入栈,则说明 $v$ 在左子树上或 $v$ 是 $u$ 的祖宗,则用 $dfn_v$ 更新 $low_u$。
3. $v$ 已被访问且未入栈,则说明 $v$ 已出栈,即已划为其他强连通分量,则不必再考虑。
:::info[Code]{open}
```cpp
for(int i=head[u];i;i=nxt[i]){
int v=to[i];
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(stag[v])
low[u]=min(low[u],dfn[v]);
}
```
:::
- 然后处理强连通分量。若 $dfn_u=low_u$,即 $u$ 的最早回溯为自己本身,则说明 $u$ 是强连通分量上的一点,此时栈内 $u$ 后的元素都为该强连通分量上的点,记录即可。
:::info[Code]{open}
```cpp
if(low[u]==dfn[u]){
++scnt;
while(true){
int top=sto.top();
sto.pop();stag[top]=0;
scc[top]=scnt;++scize[scnt];
if(top==u)break;
//这里注意边界,记得弹出边界点
}
}
```
:::
如此即可,附上完整代码。
:::success[Code]{open}
```cpp
//scc
#pragma gcc optimize(2)
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
#include <queue>
#define int long long
#define maxn 100010
#define inf 2147483647
using namespace std;
int n,m,ans=0;
int scnt=0,scc[maxn],scize[maxn];
int head[maxn],to[maxn],nxt[maxn],cnt=0;
int dfn[maxn],low[maxn],tsp=0;
stack<int> sto;
bool stag[maxn],used[maxn];
void add(int u,int v){
to[++cnt]=v;
nxt[cnt]=head[u];
head[u]=cnt;
}
void tarjan(int u){
dfn[u]=low[u]=++tsp;
sto.push(u);
stag[u]=used[u]=1;
for(int i=head[u];i;i=nxt[i]){
int v=to[i];
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(stag[v])
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u]){
++scnt;
while(true){
int top=sto.top();
sto.pop();stag[top]=0;
scc[top]=scnt;++scize[scnt];
if(top==u)break;
}
}
}
inline int read(){
int x=0,f; char ch=0;
while(!isdigit(ch)) f=(ch=='-'?-1:1),ch=getchar();
while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
return x*f;
}
inline void print(int x){
if(x<0) x=-x,putchar('-');
if(x>9) print(x/10);
putchar(x%10+48);
}
inline void write(int x){print(x);putchar('\n');}
signed main(){
n=read(),m=read();
for(int i=1;i<=m;++i)add(read(),read());
for(int i=1;i<=n;++i)
if(!used[i])tarjan(i);
for(int i=1;i<=scnt;++i)
if(scize[i]>1)++ans;
write(ans);
return 0;
}
```
:::