首页 > 代码库 > tarjan算法模板

tarjan算法模板

终于能自己完整的打下来

 

 

#include<cstdio>#include<cstring>#include<iostream>#include<vector>#include<algorithm>using namespace std;const int maxn=2020;bool isins[maxn];int low[maxn],dfn[maxn];int zhan[maxn],top=0;vector<int>tu[maxn];vector<int>lt[maxn];int lts=0;int js=0,n,m;void tarjan(int i){    int j;    dfn[i]=low[i]=++js;    isins[i]=1;    zhan[top++]=i;    for(j=0;j<tu[i].size();j++)    {        int tp=tu[i][j];        if(dfn[tp]==-1)            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]=0;            lt[lts].push_back(j);        }while(i!=j);    }}void solve(int n){    memset(dfn,-1,sizeof dfn);    memset(low,-1,sizeof low);    memset(zhan,-1,sizeof zhan);    memset(isins,0,sizeof isins);    for(int i=0;i<n;i++)      if(dfn[i]==-1)        tarjan(i);    }int main(){    cin>>n>>m;    for(int i=1;i<=m;i++)    {        int a,b;        cin>>a>>b;        tu[a].push_back(b);    }    solve(n);    for(int i=1;i<=lts;i++)    {        cout<<i<<":";        for(int j=0;j<lt[i].size();j++)            cout<<lt[i][j]<<" ";        cout<<endl;    }    return 0;}

 

tarjan算法模板