POJ 2186 Popular Cows (强连通分量)

POJ 2186 Popular Cows 


题意:每头奶牛都梦想着成为牧群中最受奶牛仰慕的奶牛。在牧群中,有N 头奶牛,1≤N≤10,000,给定M 对(1≤M≤50,000)有序对(A, B),表示A 仰慕B。由于仰慕关系具有传递性,也就是说,如果A 仰慕B,B 仰慕C,则A 也仰慕C,即使在给定的M 对关系中并没有(A, C)。你的任务是计算牧群中受每头奶牛仰慕的奶牛数量。

思路:首先可以知道,在同一个强连通分量内的点一定互相仰慕,所以可以先将强连通分量进行缩点。如果缩点之后的图不连通,一定是不行的。如果连通,那么该图就是一个DAG,若只有一个出度为0的点,那么该点内的牛都是,若有大于一个出度为0的点,那么这两个点一定不连通,所以不行。(在判断出度的时候,不连通的图已经包含在内了,所以不用特意处理)

代码:
/*
ID: wuqi9395@126.com
PROG:
LANG: C++
*/
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<fstream>
#include<cstring>
#include<ctype.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF (1<<30)
#define PI acos(-1.0)
#define mem(a, b) memset(a, b, sizeof(a))
#define rep(i, a, n) for (int i = a; i < n; i++)
#define per(i, a, n) for (int i = n - 1; i >= a; i--)
#define eps 1e-6
#define debug puts("===============")
#define pb push_back
#define mkp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define POSIN(x,y) (0 <= (x) && (x) < n && 0 <= (y) && (y) < m)
typedef long long ll;
typedef unsigned long long ULL;
const int maxn = 10100;
vector<int> g[maxn];
int n, m, dfn[maxn], low[maxn], scc_cnt, dfs_clock, sccno[maxn];
int tot[maxn];
stack<int> s;
void dfs(int u) {
    low[u] = dfn[u] = ++dfs_clock;
    s.push(u);
    for (int i = 0; i < g[u].size(); i++) {
        int v = g[u][i];
        if (!dfn[v]) {
            dfs(v);
            low[u] = min(low[v], low[u]);
        } else if (!sccno[v]) low[u] = min(low[u], dfn[v]);
    }
    if (low[u] == dfn[u]) {
        scc_cnt++;
        while(1) {
            int x = s.top();
            s.pop();
            sccno[x] = scc_cnt;
            tot[scc_cnt]++;
            if (x == u) break;
        }
    }
}
void find_scc(int n) {
    mem(dfn, 0);
    mem(sccno, 0);
    scc_cnt = dfs_clock = 0;
    for (int i = 1; i <= n; i++) if (!dfn[i]) dfs(i);
}
int degree[maxn];
int work() {
    for (int u = 1; u <= n; u++) {
        for (int i = 0; i < g[u].size(); i++) {
            int U = sccno[u], V = sccno[g[u][i]];
            if (U != V) degree[U]++;
        }
    }
    int now = 0, cnt = 0;
    for (int i = 1; i <= scc_cnt; i++) if (!degree[i]) {
            now = tot[i];
            cnt++;
            if (cnt > 1) return 0;
        }
    return now;
}
int main () {
    scanf("%d%d", &n, &m);
    int u, v;
    while(m--) {
        scanf("%d%d", &u, &v);
        g[u].pb(v);
    }
    find_scc(n);
    printf("%d\n", work());
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值