1076: Popular Cow
Time Limit: 1 Sec Memory Limit: 13 MBSubmit: 386 Solved: 131
[Submit][Status][Web Board]
Description
Every cow has a dream: to be the most popular famous cow in a group! In a herd with N (1<=N<=10,000) cattle, give you M (1<=M<=50,000) tuples (A,B), indicating that A thinks B is popular . Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A also thinks C is popular, even if it's not a very clear rule. Your task is to count the number of cows that are liked by all other cows.
Input
The first line, two numbers, N and M. Lines 2 to M+1, each line has two numbers, A and B, indicating that A thinks B is popular.
Output
A number, the number of cows considered popular by all other cows.
Sample Input
3 3 1 2 2 1 2 3
Sample Output
1
HINT
[Example description] Cow #3 is the only one considered famous by all other cows.
Summary: Tarjan shrinks the points, if the number of points with an out-degree of 0 is 0, ans = n, if the number of points with an out-degree of 0 is 1, ans = sum[this point], if the number is greater than 1, ans = 0.
#include<bits/stdc++.h> using namespace std; const int maxn = 100005; int dfn[maxn], low[maxn], head[maxn << 1]; bool vis[maxn]; int n, m, cnt = 1, sum[maxn]; struct Node{ int v, nxt; }G[maxn << 1]; void insert(int u, int v) { G[cnt] = (Node) {v, head[u]}; head[u] = cnt++; } stack<int> s; int tot = 0, color[maxn], tim = 0; void tarjan(int x) { vis[x] = true; s.push(x); dfn[x] = low[x] = ++tim; for (int i = head[x]; i; i = G[i].nxt) { int v = G[i].v; if(!dfn[v]) { tarjan(v); low[x] = min(low[x], low[v]); } else if(vis[v]) low[x] = min(low[x], dfn[v]); } if(dfn[x] == low[x]) { tot++; while(1) { int now = s.top(); vis[now] = false; s.pop(); color[now] = tot; sum[tot]++; if(now == x) break; } } } int chu[maxn]; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; ++i) { int x, y; scanf("%d%d", &x, &y); insert(x, y); } for (int i = 1; i <= n; ++i) if(!dfn[i]) tarjan(i); for (int u = 1; u <= n; ++u) { for (int i = head[u]; i; i = G[i].nxt) { int v = G[i].v; if(color[u] != color[v]) chu[color[u]]++; } } int ans = 0; int fl = 0; for (int i = 1; i <= tot; ++i) if(chu[i] == 0) ans = sum[i], fl++; if(fl > 1) printf("0\n"); else if(fl == 0) printf("%d\n", n); else printf("%d\n", ans); return 0; }