POJ 2186 Popular Cows(tarjan求强连通)

来源:互联网 发布:桌面日程安排软件 编辑:程序博客网 时间:2024/05/08 20:13


Popular Cows
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 35096 Accepted: 14308

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 31 22 12 3

Sample Output

1

Hint

Cow 3 is the only cow of high popularity. 

Source

USACO 2003 Fall


题意:

给定一些有向路,求有多少个点可以由其余的任意点到达

思路: 对于一个有向无环图来说,其中有且仅有一个点出度为零,那么这个特殊的点,可以由其他任何点到达(画几个图就知道2个以上的肯定有点不能到达)。那么接下来我们直接对所给的图进行强连通分量划分,然后把每个强连通分量看做一个点,判定出度为零的点有几个,如果有一个就输出这个点对应的强连通分量含有的节点个数,否则为零。

代码:

#include <iostream>#include <cstring>#include <cstdio>#include <vector>#include <algorithm>using namespace std;const int maxn = 1e4 + 5;const int maxe = 5e4 + 5;vector<int> v[maxe];bool vis[maxn];int n, m, k, cnt, index, sk[maxn], dfn[maxn], low[maxn], id[maxn], out[maxn];void init(){    cnt = index = k = 1;    memset(vis, 0, sizeof(vis));    memset(out, 0, sizeof(out));    memset(dfn, 0, sizeof(dfn));    for(int i = 0; i < maxe; i++)        v[i].clear();}void tarjan(int x){    low[x] = dfn[x] = cnt++;    sk[index++] = x;    vis[x] = 1;    for(int i = 0; i < v[x].size(); i++)    {        int to = v[x][i];        if(!dfn[to])        {            tarjan(to);            low[x] = min(low[x], low[to]);        }        else if(vis[to]) low[x] = min(low[x], dfn[to]);    }    if(low[x] == dfn[x])    {        do{            index--;            id[sk[index]] = k;            vis[sk[index]] = 0;        }while(sk[index] != x);        k++;    }}void solve(){    int sum = 0, ans = 0, tmp;    for(int i = 1; i <= n; i++)        for(int j = 0; j < v[i].size(); j++)            if(id[i] != id[v[i][j]])                out[id[i]]++;    for(int i = 1; i < k; i++)        if(!out[i]) sum++, tmp = i;    if(sum != 1) puts("0");    else    {        for(int i = 1; i <= n; i++)            if(id[i] == tmp) ans++;        printf("%d\n", ans);    }}int main(){    while(~scanf("%d%d", &n, &m))    {        init();        for(int i = 1; i <= m; i++)        {            int x, y;            scanf("%d%d", &x, &y);            v[x].push_back(y);        }        for(int i = 1; i <= n; i++)            if(!dfn[i]) tarjan(i);        solve();    }    return 0;}