poj2186 Popular Cows

Popular Cows
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 36087   Accepted: 14710

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.

Source

分析:先缩点,如果最后只有一个强联通分量满足出度为0,那么答案就是这个强联通分量的点的数量,否则为0.一个强连通分量要被其他所有的强连通分量指向,那么这个强连通分量肯定不能有出边,否则一定会形成一个更大的强连通分量.有且只有一个,因为满足条件的强连通分量要被剩下的强连通分量所指,如果有两个没有出边,答案自然为0.\
没有1A,因为没有考虑到强连通分量中点的数目......直接输出了1
#include <cstdio>
#include <stack>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 50010;

int n,m,head[maxn],to[maxn],nextt[maxn],tot = 1,pre[maxn],low[maxn],scc[maxn],cnt,du[maxn],dfs_clock;
int ans,numm,num[maxn];
stack <int> s;

void add(int x,int y)
{
    to[tot] = y;
    nextt[tot] = head[x];
    head[x] = tot++;
}

void tarjan(int u)
{
    s.push(u);
    pre[u] = low[u] = ++dfs_clock;
    for (int i = head[u];i;i = nextt[i])
    {
        int v = to[i];
        if (!pre[v])
        {
            tarjan(v);
            low[u] = min(low[u],low[v]);
        }
        else
            if (!scc[v])
                low[u] = min(low[u],pre[v]);
    }
    if (pre[u] == low[u])
    {
        cnt++;
        while(1)
        {
            int t = s.top();
            s.pop();
            scc[t] = cnt;
            num[cnt]++;
            if(t == u)
                break;
        }
    }
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= m; i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b);
    }
    for (int i = 1; i <= n; i++)
        if (!pre[i])
            tarjan(i);
    for (int i = 1; i <= n; i++)
    {
        for(int j = head[i];j;j = nextt[j])
        {
            int v = to[j];
            if (scc[i] != scc[v])
                du[scc[i]]++;
        }
    }
    for (int i = 1; i <= cnt; i++)
        if (!du[i])
        {
            numm++;
            ans = num[i];
        }
    if (numm == 1)
    printf("%d\n",ans);
    else
        printf("0\n");

    return 0;
}

 

posted @ 2017-12-15 14:22  zbtrs  阅读(174)  评论(0编辑  收藏  举报