参考神犇的博客:https://www.cnblogs.com/stxy-ferryman/p/7779347.html
强联通分量:
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=100010,maxm=1000010;
int dfn[maxn],low[maxn],head[maxn],color[maxn];
int n,m,k,deep,cnt;
bool vis[maxn];
struct edge{
int v,next;
}e[maxm];
stack<int> s;
void addedge(int u,int v){e[k].v=v;e[k].next=head[u];head[u]=k++;}
void tarjan(int u)
{
deep++;
dfn[u]=deep;
low[u]=deep;
vis[u]=1;
s.push(u);
for(int i=head[u];~i;i=e[i].next)
{
int v=e[i].v;
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else
{
if(vis[v])
{
low[u]=min(low[u],low[v]);
}
}
}
if(dfn[u]==low[u])
{
cnt++;
color[u]=cnt;
vis[u]=0;
while(s.top()!=u)
{
color[s.top()]=cnt;
vis[s.top()]=0;
s.pop();
}
s.pop();
}
}
求割点:
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=100010,maxm=1000010;
int dfn[maxn],low[maxn],head[maxn],color[maxn];
int n,m,k,deep,cnt;
bool iscut[maxn];
struct edge{
int v,next;
}e[maxm];
stack<int> s;
void addedge(int u,int v){e[k].v=v;e[k].next=head[u];head[u]=k++;}
int tarjan(int u,int fa)
{
int child=0,lowu;
deep++;
dfn[u]=deep;
lowu=deep;
for(int i=head[u];~i;i=e[i].next)
{
int v=e[i].v;
if(!dfn[v])
{
child++;
int lowv=tarjan(v,u);
lowu=min(lowu,lowv);
if(lowu>dfn[u])
iscut[u]=1;
}
else
{
if(v!=fa&&dfn[v]<dfn[u])
lowu=min(lowu,dfn[v]);
}
}
if(fa<0&&child==1)
iscut[u]=0;
low[u]=lowu;
return lowu;
}
int main()
{
for(int i=1;i<=n;i++)
{
if(!dfn[i])
{
root=i;
tarjan(i,-1);
}
}
return 0;
}
求桥:
#include<iostream>
#include<cstdio>
#include<stack>
#include<vector>
using namespace std;
const int maxn=100010,maxm=1000010;
int dfn[maxn],low[maxn],head[maxn],color[maxn];
int n,m,k,deep,cnt;
bool iscut[maxn];
struct edge{
int v,next;
}e[maxm];
stack<int> s;
vector<pair<int,int> >bridge;
void addedge(int u,int v){e[k].v=v;e[k].next=head[u];head[u]=k++;}
int tarjan(int u,int fa)
{
int lowu;
deep++;
dfn[u]=deep;
lowu=deep;
for(int i=head[u];~i;i=e[i].next)
{
int v=e[i].v;
if(!dfn[v])
{
int lowv=tarjan(v,u);
lowu=min(lowu,lowv);
if(lowu>dfn[u])
{
int from,to;
from=u;
to=v;
if(from>to) swap(from,to);
bridge.push_back(make_pair(from,to));
}
}
else
{
if(v!=fa&&dfn[v]<dfn[u])
lowu=min(lowu,dfn[v]);
}
}
low[u]=lowu;
return lowu;
}
int main()
{
for(int i=1;i<=n;i++)
{
if(!dfn[i])
{
root=i;
tarjan(i,-1);
}
}
return 0;
}