Tarjan Algorithm Template

1. Introduction to the algorithm

Tarjan's algorithm is an algorithm proposed by Robert Tarjan to solve the strongly connected components of a directed graph, which can achieve linear time complexity.

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
#include<map>
#include<vector>
#include<queue>
#include<set>
using namespace std;
const int size = 100000;
struct node
{
    int to,next;
}bian[1990];
int DFN[1000],LOW[1000];
int staack[1000],head[1000],visit[1000],cnt,tot,index;
void add(int a,int b)
{
    bian[tot].to=b;
    bian[tot].next=head[a];
    head[a]=tot++;
}
void tarjan(int a)
{
    DFN[a]=LOW[a]=++cnt;
    staack[++index]=a;
    visit[a]=1;
    for(int i=head[a];i!=-1;i=bian[i].next)
    {
        if(!DFN[bian[i].to])
        {
            tarjan(bian[i].to);
            LOW[a]=min(LOW[a],LOW[bian[i].to]);
        }
        else if(visit[bian[i].to])
        {
            LOW[a]=min(LOW[a],DFN[bian[i].to]);
        }
    }
    if(LOW[a]==DFN[a])
    {
        do
        {
            cout<<staack[index];
            visit[staack[index]]=0;
            index--;
        }while(a!=staack[index+1]);
        cout<<endl;
    }
    return ;
}
intmain ()
{
    memset(head,-1,sizeof(head));
    int n,m;
    cin>>n>>m;
    int x,y;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        add(x,y);
    }
    for(int i=1;i<=n;i++)
    {
        if(!DFN[i])tarjan(i);
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325285794&siteId=291194637