POJ 2553 The Bottom of a Graph

求图的底,就是找出经过缩点后的图中出度为0的点, 每个点中的元素就是图的底。然后

有序输出,不要多输出空格。将tarjan算法敲的比较熟了。

/*Accepted    468K    47MS    C++    1864B    2012-07-30 14:44:59*/

#include<cstdio>

#include<cstring>

#include<cstdlib>



const int MAXN = 5050;

const int MAXM = MAXN * MAXN;

int first[MAXN], next[MAXM], v[MAXM], cnt, top, col, e, N, M, k;

int dfn[MAXN], s[MAXN], low[MAXN], outdgr[MAXN], color[MAXN], ins[MAXN];



void tarjan(int cur)

{

    int i;

    dfn[cur] = low[cur] = ++ cnt;

    s[top ++] = cur, ins[cur] = 1;

    for(i = first[cur]; i != -1; i = next[i])

    {

        if(!dfn[v[i]])

        {

            tarjan(v[i]);

            if(low[v[i]] < low[cur])

                low[cur] = low[v[i]];

        }

        else if(dfn[v[i]] < low[cur] && ins[v[i]])

            low[cur] = dfn[v[i]];

    }

    if(low[cur] == dfn[cur])

    {

        ++ col;

        for(s[top] = -1; s[top] != cur; )

            color[s[-- top]] = col, ins[s[top]] = 0;

    }

}



void cal()

{

    int i, j;

    cnt = top = col = 0;

    memset(dfn, 0, sizeof dfn);

    memset(ins, 0, sizeof ins);

    for(i = 1; i <= N; i ++)

        if(!dfn[i])

            tarjan(i);

    memset(outdgr, 0, sizeof outdgr);

    for(i = 1; i <= N; i ++)

        for(j = first[i]; j != -1; j = next[j])

            if(color[i] != color[v[j]])

                ++ outdgr[color[i]];

    k = 0;

    for(i = 1; i <= N; i ++)

    {

        if(outdgr[color[i]] == 0)

        {

            if(k ++) printf(" ");

            printf("%d", i);

        }

    }

    printf("\n");

}



void addedge(int x, int y)

{

    v[e] = y;

    next[e] = first[x], first[x] = e ++;

}



void ReadGraph()

{

    int x, y;

    e = 0;

    memset(first, -1, sizeof first);

    while(M --)

    {

        scanf("%d%d", &x, &y);

        addedge(x, y);

    }

}



int main()

{

    while(scanf("%d", &N) != EOF)

    {

        if(N == 0) break;

        scanf("%d", &M);

        ReadGraph();

        cal();

    }

    return 0;

}

 

 

你可能感兴趣的:(Graph)