POJ 2186 Tarjan 统计唯一出度为0的强联通块包含的结点数

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxv=10010;
const int maxe=50010;
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;
            num[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,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]]++;
                }
            }
        }
        int cnt=0,index;
        for(int i=1;i<=scc;i++)
            if(out[i]==0)//必须保证出度为0的强连通块只有一块,要不他就不是最受欢迎的了
                cnt++,index=i;
        if(cnt==1)
            cout<<num[index]<<endl;
        else
            cout<<0<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/81356870