tarjan算法模板

终于能自己完整的打下来

#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=;
bool isins[maxn];
int low[maxn],dfn[maxn];
int zhan[maxn],top=;
vector<int>tu[maxn];
vector<int>lt[maxn];
int lts=;
int js=,n,m;
void tarjan(int i)
{
int j;
dfn[i]=low[i]=++js;
isins[i]=;
zhan[top++]=i;
for(j=;j<tu[i].size();j++)
{
int tp=tu[i][j];
if(dfn[tp]==-)
tarjan(tp),
low[i]=min(low[i],low[tp]);
else if(isins[tp])
low[i]=min(low[i],dfn[tp]);
}
if(dfn[i]==low[i])
{
lts++;
do{
j=zhan[--top];
isins[j]=;
lt[lts].push_back(j);
}while(i!=j);
}
}
void solve(int n)
{
memset(dfn,-,sizeof dfn);
memset(low,-,sizeof low);
memset(zhan,-,sizeof zhan);
memset(isins,,sizeof isins);
for(int i=;i<n;i++)
if(dfn[i]==-)
tarjan(i); }
int main()
{
cin>>n>>m;
for(int i=;i<=m;i++)
{
int a,b;
cin>>a>>b;
tu[a].push_back(b);
}
solve(n);
for(int i=;i<=lts;i++)
{
cout<<i<<":";
for(int j=;j<lt[i].size();j++)
cout<<lt[i][j]<<" ";
cout<<endl;
}
return ;
}
上一篇:androidService总结


下一篇:HDOJ 1011 Starship Troopers