Tip
定义
对于有向图 ,有 点 ,满足 且 ,则称 强连通。若 满足任意 点强连通,则称 为强连通图,一张图的强连通分量为其极大强连通子图。
前置
:时间戳,即 在图中被 dfs 搜索到的顺序。
:回溯值,即 在图中可访问到的最早时间戳。
看一个例子:
如图,以 节点作为搜索起始点。
则 为 , 为 。
实现
例题:P2863 [USACO06JAN] The Cow Prom S
- 对于 dfs 到的点 ,更新 与 ,并将 入栈,由于图不一定连通,所以标记访问数组 以便主函数跑 tarjan。
Code
dfn[u]=low[u]=++tsp;
//tsp为全局时间戳变量
sto.push(u);
stag[u]=used[u]=1;- 接着开始跳边遍历,记邻点为 。
对于 ,有如下可能:
- 未被访问,即未更新 ,则对其搜索。由于该情况下 为 的子节点,故用其 更新当前节点 。
- 已被访问且入栈,则说明 在左子树上或 是 的祖宗,则用 更新 。
- 已被访问且未入栈,则说明 已出栈,即已划为其他强连通分量,则不必再考虑。
Code
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]);
}- 然后处理强连通分量。若 ,即 的最早回溯为自己本身,则说明 是强连通分量上的一点,此时栈内 后的元素都为该强连通分量上的点,记录即可。
Code
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;
//这里注意边界,记得弹出边界点
}
}如此即可,附上完整代码。
Code
//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;
}