P2341 [HAOI2006]受欢迎的牛 Tarjan + 缩点

题目背景

本题测试数据已修复。

题目描述

每头奶牛都梦想成为牛棚里的明星。被所有奶牛喜欢的奶牛就是一头明星奶牛。所有奶

牛都是自恋狂,每头奶牛总是喜欢自己的。奶牛之间的“喜欢”是可以传递的——如果A喜

欢B,B喜欢C,那么A也喜欢C。牛栏里共有N 头奶牛,给定一些奶牛之间的爱慕关系,请你

算出有多少头奶牛可以当明星。

输入格式:

 第一行:两个用空格分开的整数:N和M

 第二行到第M + 1行:每行两个用空格分开的整数:A和B,表示A喜欢B

输出格式:

 第一行:单独一个整数,表示明星奶牛的数量

输入样例
3 3
1 2
2 1
2 3
输出样例
1 

说明

只有 3 号奶牛可以做明星

【数据范围】

10%的数据N<=20, M<=50

30%的数据N<=1000,M<=20000

70%的数据N<=5000,M<=50000

100%的数据N<=10000,M<=50000

题解:

本题利用结论:在DAG中, 如果 有且仅有 一个点的出度为0 ,那么该点可以被所有点遍历到;反之,该图中没有可以被所有点遍历到的点。

至于证明,我不会 利用用反证法证明;

#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
const int N = 1e4 + 5;
int n, m, ans;
struct edge { int to, nxt; } e[50005];
int cnt, head[N], chu[N], size[N];
void add(int from, int to) {
    e[++ cnt].to = to;
    e[cnt].nxt = head[from];
    head[from] = cnt;
}
stack <int> s;
int dfn[N], low[N], tot, scc, tar[N];
void tarjan(int x) {
    dfn[x] = low[x] = ++ tot;
    s.push(x);
    for(int i = head[x]; i ;i = e[i].nxt) {
        int to = e[i].to;
        if(! dfn[to]) {
            tarjan(to);
            low[x] = min(low[x], low[to]);
        }
        else if(! tar[to])
            low[x] = min(low[x], dfn[to]);
    }
    if(dfn[x] == low[x]) {
        scc ++;
        while(1) {
            int y = s.top(); s.pop();
            tar[y] = scc; size[scc] ++;
            if(y == x) break;
        };
    }
}
int main() {
    cin >> n >> m;
    for(int i = 1, x, y;i <= m;i ++) cin >> x >> y, add(x, y);
    for(int i = 1;i <= n;i ++) if(! low[i]) tarjan(i);
     for(int x = 1;x <= n;x ++) {
        for(int i = head[x]; i ;i = e[i].nxt) {
            int y = e[i].to;
            if(tar[x] == tar[y]) continue;
            chu[tar[x]] ++;
        }
    }
    for(int i = 1;i <= scc;i ++) {
        if(chu[i] == 0) {
            if(ans) { ans = 0; break; }
            ans += size[i];
        }
    }
    cout << ans << endl;
    return 0;
}

 

posted @ 2019-07-22 20:50  Paranoid丶离殇  阅读(133)  评论(0编辑  收藏  举报