有向图的强联通分量 tarjan

多与DAG上的DP之类的问题一起出现。


using namespace std;

const int MAXE = 300010;
const int MAXP = 100010;

struct N
{
    int v,next;
}edge[MAXE];
int head[MAXP];
int Top;
int ty[MAXP];
int high[MAXP];
int lowlink[MAXP];
int SCCans,dfsclock;
int S[MAXP],STop;

void InitGraph()
{
    SCCans = dfsclock = 0;
    memset(high,0,sizeof(high));
    memset(ty,0,sizeof(ty));
    memset(head,-1,sizeof(head));
    Top = 0;
    STop = 0;
}

void Link(int u,int v)
{
    edge[Top].next = head[u];
    edge[Top].v = v;
    head[u] = Top++;
}

void dfs(int s)
{
    high[s] = lowlink[s] = ++dfsclock;
    S[STop++] = s;
    int i,v;
    for(i = head[s] ; i != -1; i = edge[i].next)
    {
        v = edge[i].v;

        if(high[v] == 0)
        {
            dfs(v);
            lowlink[s] = min(lowlink[s],lowlink[v]);
        }
        else if(ty[v] == 0)
        {
            lowlink[s] = min(lowlink[s],lowlink[v]);
        }
    }

    if(lowlink[s] == high[s])
    {
        SCCans++;
        do
        {
            v = S[--STop];
            ty[v] = SCCans;
        }while(s != v);
    }
}

vector<int> vec[MAXP];

int main()
{
    int n,m,u,v,i,j;

    while(scanf("%d %d",&n,&m) != EOF)
    {
        InitGraph();

        while(m--)
        {
            scanf("%d %d",&u,&v);

            Link(u,v);
        }

        for(i = 1;i <= n; ++i)
            if(ty[i] == 0)
                dfs(i);

        for(i = 1;i <= SCCans; ++i)
            vec[i].clear();

        for(i = 1;i <= n; ++i)
        {
            for(j = head[i];j != -1;j = edge[j].next)
            {
                if(ty[i] != ty[edge[j].v])
                    vec[ty[i]].push_back(ty[edge[j].v]);
            }
        }
    }

    return 0;
}











郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。