POJ 2553 Tarjan 统计出度为0的强连通块

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxv=5010;
const int maxe=1000000;
int Index,top,scc,cnt;
bool Instack[maxv];
int head[maxv],Low[maxv],DFN[maxv],Belong[maxv],Stack[maxv],num[maxv],out[maxv],in[maxv];
struct Edge {
    int to,next;
} edge[maxe];
void addedge(int from,int to) {
    edge[cnt].to=to;
    edge[cnt].next=head[from];
    head[from]=cnt++;
}
void Tarjan(int u) {
    int v;
    Low[u] = DFN[u] = ++Index;  //刚搜到一个节点时Low = DFN;
    Stack[top++] = u;  //将该节点入栈
    Instack[u] = 1;  //将入栈标记设置为1
    for (int i = head[u]; i != -1; i = edge[i].next) {
        v = edge[i].to;
        if(!DFN[v]) {
            Tarjan( v);
            if( Low[u] > Low[v] )
                Low[u] = Low[v];
        } else if(Instack[v] && Low[u] > DFN[v])
            Low[u] = DFN[v];
    }
    if(Low[u] == DFN[u]) {
        scc++;
        do {
            v = Stack[--top];
            Instack[v] = false;
            Belong[v] = scc;
        } while( v != u);
    }
}
void solve(int n) {
    memset(DFN,0,sizeof DFN);
    memset(Instack,false,sizeof Instack);
    Index=scc=top=0;
    for(int i=1; i<=n; i++)
        if(!DFN[i])
            Tarjan(i);
}
void init() {
    cnt=0;
    memset(head,-1,sizeof head);
    memset(out,0,sizeof out);
}
int main(void) {
#ifndef ONLINE_JUDGE
    freopen("E:\\input.txt","r",stdin);
#endif // ONLINE_JUDGE
    int n,m,num,t1,t2;
    while(cin>>n&&n) {
        cin>>m;
        init();
        for(int i=1; i<=m; i++) {
            cin>>t1>>t2;
            addedge(t1,t2);
        }
        solve(n);
        for(int i=1; i<=n; i++) {
            for(int j=head[i]; j!=-1; j=edge[j].next) {
                int v=edge[j].to;
                if(Belong[i]!=Belong[v]) {
                    out[Belong[i]]++;
                }
            }
        }
        bool flag=false;
        for(int i=1; i<=n; i++) {
            if(out[Belong[i]]==0)
                if(!flag) {
                    cout<<i;
                    flag=1;
                } else
                    cout<<" "<<i;
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/81356556
今日推荐