天天看点

poj 2186 Popular Cows

题目链接:​​Popular Cows​​

#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <utility>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;
typedef long long ll;
const int maxn = 20010;

vector<int>Edge[maxn];
stack<int>S;

int Dfn[maxn],Low[maxn],sccno[maxn],tclock,sccnt;
int OutDeg[maxn],numscc[maxn],popu;

void tarjan(int u){
    Dfn[u] = Low[u] = ++tclock;
    S.push(u);

    for(int i = 0;i < Edge[u].size();i++){
        int v = Edge[u][i];
        if(!Dfn[v]){
            tarjan(v);
            Low[u] = min(Low[u],Low[v]);
        }
        else if(!sccno[v]){
            Low[u] = min(Low[u],Dfn[v]);
        }
    }

    if(Low[u] == Dfn[u]){
        sccnt ++;
        int v = -1;
        while(v != u){
            v = S.top();
            S.pop();
            sccno[v] = sccnt;
            numscc[sccnt]++;
        }
    }
}

void findscc(int n){
    tclock = sccnt = 0;
    memset(Dfn,0,sizeof(Dfn));
    memset(Low,0,sizeof(Low));
    memset(sccno,0,sizeof(sccno));
    memset(numscc,0,sizeof(numscc));
    for(int i = 1;i <= n;i++)
        if(!Dfn[i]) tarjan(i);
}

int solve(int n){
    memset(OutDeg,0,sizeof(OutDeg));
    popu = 0;
    for(int u = 1;u <= n;u++){
        for(int i = 0;i < Edge[u].size();i++){
            int v = Edge[u][i];
            if(sccno[u] != sccno[v]){
                OutDeg[sccno[u]]++;
            }
        }
    }

    int c = 0;
    for(int i = 1;i <= sccnt;i++){
        if(OutDeg[i] == 0){
            if(c == 0) {popu = numscc[i];c++;}
            else popu = 0;
        }
    }
    return popu;
}

int main(){
    int T,n,m;
    while(~scanf("%d%d",&n,&m)){
        for(int i = 1;i <= n;i++) Edge[i].clear();
        while(m--){
            int u,v;
            scanf("%d%d",&u,&v);
            Edge[u].push_back(v);
        }
        findscc(n);
        printf("%d\n",solve(n));
    }
    return 0;
}