码迷,mamicode.com
首页 > 移动开发 > 详细

有向图的强联通分量 tarjan

时间:2015-05-15 12:10:51      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

多与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;
}











有向图的强联通分量 tarjan

标签:

原文地址:http://blog.csdn.net/zmx354/article/details/45741571

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!