POJ 2186 Popular Cows 强连通分量

来源:互联网 发布:天刀女神威捏脸数据 编辑:程序博客网 时间:2024/05/16 14:40

统计能被其他所有点访问的点的个数。
这里建边是<a,b>
缩点以后没有出边的就是符合题意的,但是只能有1个连通分量没有出边。

#include <cstdio>#include <cstring>#define min(i,j) ((i)<(j)?(i):(j))#define ms(a, b) memset(a, b, sizeof(a))const int N = 10001, M = 50001;int h[N], p[M], v[M], belong[N], out[N], dfn[N], low[N];int scc, top, ts, cnt, stack[N], instack[N];void add(int a, int b) { p[++cnt] = h[a]; v[cnt] = b; h[a] = cnt; }void tarjan(int u) {    int i;    dfn[u] = low[u] = ++ts;    stack[++top] = u; instack[u] = 1;    for (i = h[u]; i; i = p[i])        if (!dfn[v[i]]) {            tarjan(v[i]);            low[u] = min(low[u], low[v[i]]);        } else if (instack[v[i]])            low[u] = min(low[u], dfn[v[i]]);    if (dfn[u] == low[u]) {        ++scc;        do {            i = stack[top--];            instack[i] = 0;            belong[i] = scc;        } while (i != u);    }}int main() {    int i, j, n, m, a, b;    while (scanf("%d%d", &n, &m) == 2) {        ms(dfn, 0); ms(out, 0); ms(h, 0);        ts = cnt = top = scc = 0;        for (i = 0; i < m; ++i) scanf("%d%d", &a, &b), add(a, b);        for (i = 1; i <= n; ++i)            if (!dfn[i]) tarjan(i);        for (i = 1; i <= n; ++i)            for (j = h[i]; j; j = p[j])                if (belong[i] != belong[v[j]])                    ++out[belong[i]];        a = 0;        for (i = 1; i <= scc; ++i)            if (!out[i]) ++a;        if (a != 1) {            puts("0");            continue;        }        a = 0;        for (i = 1; i <= n; ++i)            if (!out[belong[i]]) ++a;        printf("%d\n", a);    }    return 0;}

Popular Cows

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 28605 Accepted: 11569

Description

Every cow’s dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.

Input

  • Line 1: Two space-separated integers, N and M

  • Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.

Output

  • Line 1: A single integer that is the number of cows who are considered popular by every other cow.

Sample Input

3 3
1 2
2 1
2 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity.

0 0