【BZOJ1051】[HAOI2006]受欢迎的牛

【BZOJ1051】[HAOI2006]受欢迎的牛

题面

bzoj

洛谷

题解

假如\(A\)喜欢\(B\)就连一条\(A\)\(B\)的边

然后缩点,如果图不连通就\(Impossible\)

否则输出出度为\(0\)的环的大小

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

inline int gi(){
    register int data=0, w = 1;
    register char ch=0;
    while (ch != '-' && (ch > '9' || ch < '0')) ch = getchar();
    if (ch == '-') w = -1 , ch = getchar();
    while (ch >= '0' && ch <= '9') data = (data << 1) + (data << 3) + (ch ^ 48), ch = getchar();
    return w * data;
} 
#define MAX_N 10005
#define MAX_M 50005 
struct Edge { 
    int to, next; 
} e[MAX_M]; 
int h[MAX_N], cnt; 
int n, m; 
void Add_Edge(int u, int v) { 
    e[cnt].to = v, e[cnt].next = h[u], h[u] = cnt++; 
} 
int tim = 0, num = 0, top = 0; 
int low[MAX_N], dfn[MAX_N], color[MAX_N], st[MAX_N]; 
int tot[MAX_N]; 
void tarjan(int x) { 
    low[x] = dfn[x] = ++tim; 
    st[++top] = x; 
    for (register int i = h[x]; ~i; i = e[i].next) { 
        if (!dfn[e[i].to]) { 
            tarjan(e[i].to); 
            low[x] = min(low[x], low[e[i].to]); 
        } else if (!color[e[i].to]) 
            low[x] = min(low[x], dfn[e[i].to]); 
    } 
    if (low[x] == dfn[x]) { 
        color[x] = ++num; 
        tot[num]++; 
        while (st[top] != x) { 
            color[st[top]] = num; 
            tot[num]++; 
            --top; 
        } 
        --top; 
    }
} 
int d[MAX_N]; 
int main () { 
    memset(h, -1, sizeof(h)); 
    n = gi(), m = gi(); 
    for (register int i = 1; i <= m; i++) { 
        int u = gi(), v = gi(); 
        Add_Edge(u, v); 
    } 
    for (register int i = 1; i <= n; i++) 
        if (!dfn[i]) tarjan(i); 
    int ans = 0, F = 0; 
    for (register int x = 1; x <= n; x++) 
        for (int i = h[x]; ~i; i = e[i].next) 
        if (color[x] != color[e[i].to]) d[color[x]]++; 
    for (register int i = 1; i <= num; i++) {
        if (d[i] == 0) F++, ans = tot[i]; 
    } 
    if (F == 1) printf("%d\n", ans); 
    else printf("0\n");   
    return 0; 
}

转载于:https://www.cnblogs.com/heyujun/p/10179180.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值