POJ - 2186 Popular Cows tarjan缩点+思维

题目链接

题意:有n个奶牛,m条关系,每条关系A,B表示奶牛A喜欢奶牛B,若是有A喜欢B,B喜欢C,则有A喜欢C,现在问被其余n-1头奶牛喜欢的奶牛有多少个。

思路:可能存在环,所以我们先缩点,这样的话就变成一个有向无环的新图,根据这个性质,那么没有出度的点即为答案了,因为若是有出度的点为答案那么其余点必也有边指向它,那么通过缩点能缩成一个点,所以没有出度的点即为答案,但是没有出度的点只能有一个解才合法。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<queue>
#include<deque>
using std::min;
#define ll long long
#define PI acos(-1)
#define INF 0x3f3f3f3f
#define NUM 500020
#define debug true
#define lowbit(x) ((-x)&x)
#define ffor(i,d,u) for(int i=(d);i<=(u);++i)
#define _ffor(i,u,d) for(int i=(u);i>=(d);--i)
#define mst(array,Num,Kind,Count) memset(array,Num,sizeof(Kind)*(Count))
const int P = 1e9+7;
int n,m;
struct edge
{
    int f,to,next;
}e[NUM];
int h[NUM/5]={},dfn[NUM/5],low[NUM/5],check[NUM/5]={},depth = 0;
int s = 0,index[NUM/5],snum[NUM/5]={},sta[NUM/5],top = 0;
bool out[NUM/5]={};
int ans;
template <typename T>
void read(T& x)
{
    x=0;
    char c;T t=1;
    while(((c=getchar())<'0'||c>'9')&&c!='-');
    if(c=='-'){t=-1;c=getchar();}
    do(x*=10)+=(c-'0');while((c=getchar())>='0'&&c<='9');
    x*=t;
}
template <typename T>
void write(T x)
{
    int len=0;char c[21];
    if(x<0)putchar('-'),x*=(-1);
    do{++len;c[len]=(x%10)+'0';}while(x/=10);
    _ffor(i,len,1)putchar(c[i]);
}
void tarjan(int vertex)
{
    int x;
    dfn[vertex] = low[vertex] = ++depth;
    sta[top] = vertex,++top;
    check[vertex] = 1;
    for(int i=h[vertex];i!=0;i=e[i].next)
    {
        x = e[i].to;
        if(check[x] == 2)continue;
        if(!check[x])
        {
            tarjan(x);
            low[vertex] = min(low[vertex],low[x]);
        }
        else
            low[vertex] = min(low[vertex],dfn[x]);
    }
    if(low[vertex] == dfn[vertex])
    {
        ++s;
        do
        {
            x = sta[top-1];
            index[x] = s;
            check[x] = 2;
            ++snum[s],--top;
        }while(x != vertex);
    }
}
inline void AC()
{
    int x,y;
    read(n),read(m);
    ffor(i,1,m)
    {
        read(x),read(y);
        e[i].f = x,e[i].to = y,e[i].next = h[x],h[x] = i;
    }
    ffor(i,1,n)if(!check[i])tarjan(i);
    ffor(i,1,m)
    {
        int fx = index[e[i].f],fy = index[e[i].to];
        if(fx != fy)out[fx] = true;
    }
    int flag = 0;
    ffor(i,1,s)if(!out[i])++flag,ans = snum[i];
    if(flag > 1)puts("0");
    else write(ans),putchar('\n');
}
int main()
{
    AC();
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值