题意:有n头牛,某头牛可能会认为另一头牛受欢迎,现在给你m种关系,每种关系A B表示A认为B是受欢迎的,这种受欢迎有传递性,如果A认为B受欢迎,B认为C受欢迎,那么A认为C受欢迎,现在问你被其他所有人认为受欢迎的牛有多少头。
对关系图缩点后,其实就是要求出度为0的强连通,如果这样的强连通大于1,那么就没有这样的牛。如果得到的是多个有向无环图,那么也没有这样的牛,其实这种情况已经被包括进来了,因为如果有多个有向无环图,必然有大于1个的出度为0的强连通分量。
#include <stdio.h> #include <string.h> const int maxn = 10005; const int maxm = 50005; struct EDGE{ int to, vis, next; }edge[maxm]; int head[maxn], dfn[maxn], low[maxn], st[maxn], belo[maxn], ins[maxn], chudu[maxn]; int E, type, time, top; void newedge(int u, int to) { edge[E].to = to; edge[E].next = head[u]; edge[E].vis = 0; head[u] = E++; } void init() { memset(ins, 0, sizeof(ins)); memset(head, -1, sizeof(head)); memset(dfn, 0, sizeof(dfn)); memset(chudu, 0, sizeof(chudu)); E = top = type = time = 0; } int min(int a, int b) { return a > b ? b : a; } void dfs(int u) { dfn[u] = low[u] = ++time; st[++top] = u; ins[u] = 1; for(int i = head[u];i != -1;i = edge[i].next) { int to = edge[i].to; if(!dfn[to]) { dfs(to); low[u] = min(low[u], low[to]); } else if(ins[to]) { low[u] = min(low[u], low[to]); } } if(low[u] == dfn[u]) { type++; int to; do { to = st[top--]; ins[to] = 0; belo[to] = type; }while(to != u); } } void DFS(int u) { for(int i = head[u];i != -1;i = edge[i].next) { if(edge[i].vis) continue; edge[i].vis = 1; int to = edge[i].to; DFS(to); if(belo[u] != belo[to]) chudu[belo[u]] ++; } } int main() { init(); int n, m, i, u, to, j; scanf("%d%d", &n, &m); for(i = 0;i < m; i++) { scanf("%d%d", &u ,&to); newedge(u, to); } for(i = 1;i <= n ;i++) if(!dfn[i]) dfs(i); for(i = 1;i <= n; i++) DFS(i); int ok = 0, id = 1; for(i = 1;i <= type; i++) if(chudu[i] == 0) ok++, id = i; if(ok == 1) { int ans = 0; for(j = 1;j <= n; j++) if(belo[j] == id) ans++; printf("%d\n", ans); } else puts("0"); return 0; }