# poj-2186-Popular Cows (tarjan算法)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include <string>
#include <algorithm>
#define ll long long
using namespace std;
const int inf=0x3ffffff;
const int MAXN = 10003;
const double eps = 1e-6;

int next[MAXN<<3], to[MAXN<<3], head[MAXN<<3], tot;
int scc, dep;
int dfn[MAXN], low[MAXN], id[MAXN];
bool mark[MAXN];
stack<int> sta;

void tarjan(int v) {
dfn[v] = low[v] = ++dep;
sta.push(v);
mark[v] = true;
int k;
for (k = head[v]; k != -1; k = next[k]) {
if (!dfn[to[k]]) {
tarjan(to[k]);
low[v] = min(low[v], low[to[k]]);
} else if (mark[to[k]]) {
low[v] = min(low[v], dfn[to[k]]);
}
}
if (low[v] == dfn[v])  {
++scc;
int u;
do {
u = sta.top();
sta.pop();
mark[u] = false;
id[u] = scc;
} while(u != v);
}
}

int main(){
#ifndef ONLINE_JUDGE
freopen("1.txt", "r", stdin);
#endif
int i, j, k, u, v;
int n, m;
while(cin >> n >> m) {
memset(dfn, 0, sizeof(dfn));
memset(mark, false, sizeof(mark));
while(!sta.empty()){
sta.pop();
}
dep = 1;
for (i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
to[i] = v;
}
scc = 0;
for (i = 1; i <= n; i++) {
if (!dfn[i]) {
tarjan(i);
}
}
memset(mark, false, sizeof(mark));
for (i = 1; i <= n; i++) {
for (j = head[i]; j != -1; j = next[j]) {
if (id[i] != id[to[j]]) {
mark[id[i]] = true;
}
}
}
int p;
int cnt = 0;
for (i = 1; i <= scc; i++) {
if (!mark[i]) {
cnt++;
p = i;
}
}
if (cnt > 1) {
printf("0\n");
} else {
cnt = 0;
for (i = 1; i <= n; i++) {
if (id[i] == p) {
cnt++;
}
}
cout << cnt << endl;
}
}
return 0;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客