[模板] scc/强连通分量
程序员文章站
2022-07-07 20:16:25
类比无向图连通分量。low[x],dfn[x]#include using namespace std;typedef long long ll;#define ls (o<<1)#define rs (o<<1|1)#define pb push_backconst double PI= acos(-1.0);const int M = 1e5+7;const int N = 1e5+7;int head[N],...
类比无向图连通分量。
low[x],dfn[x]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ls (o<<1)
#define rs (o<<1|1)
#define pb push_back
const double PI= acos(-1.0);
const int M = 1e5+7;
const int N = 1e5+7;
int head[N],cnt=1;
void init(){cnt=1,memset(head,0,sizeof(head));}
struct EDGE{int to,nxt,w;}ee[M*2];
void add(int x,int y,int w){ee[++cnt].nxt=head[x],ee[cnt].w=w,ee[cnt].to=y,head[x]=cnt;}
int n,m,num,top,ct;
int sk[N],ins[N],c[N];
int dfn[N],low[N];
vector<int>scc[N];
void tarjan(int x)
{
dfn[x]=low[x]=++num;
sk[++top]=x,ins[x]=1;
//cout<<x<<" - "<<endl;
for(int i=head[x];i;i=ee[i].nxt)
{
int y=ee[i].to;
if(!dfn[y])
{
tarjan(y);
low[x]=min(low[x],low[y]);
}
else if(ins[y])low[x]=min(low[x],dfn[y]);
}
if(dfn[x]==low[x])
{
ct++;int y;
do{
y=sk[top--],ins[y]=0;
c[y]=ct,scc[ct].pb(y);
}while(x!=y);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
add(x,y,1);
}
for(int i=1;i<=n;i++)
if(!dfn[i])tarjan(i);
for(int i=1;i<=ct;i++)//ct个强连通分量
{
for(auto x:scc[i])
cout<<x<<" ";
cout<<endl;
}
return 0;
}
本文地址:https://blog.csdn.net/bjfu170203101/article/details/107208719