POJ 2186 Popular Cows 强连通分量模板

  题意

    强连通分量,找独立的块

  强连通分量裸题

  

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

const int maxn = 50005;
int n, m;
struct Edge
{
    int v, next;
    Edge (int v = 0, int next = 0):
        v(v), next(next) {}
}e[maxn*2];
int head[maxn], label;
int stack[maxn], Scnt;
int belong[maxn], Bcnt;
int dfn[maxn], low[maxn], dfs_clock;
bool instack[maxn];
int siz[maxn], chu[maxn];

void ins(int u, int v)
{
    e[++label] = Edge(v, head[u]);
    head[u] = label;
}

void dfs(int u)
{
    dfn[u] = low[u] = ++dfs_clock;
    stack[++Scnt] = u;
    instack[u] = true;
    for (int i = head[u]; i != -1; i = e[i].next)
    {
        int v = e[i].v;
        if (!dfn[v])
        {
            dfs(v);
            low[u] = min(low[u], low[v]);
        }
        else
            if (instack[v])
                low[u] = min(low[u], dfn[v]);
    }
    if (low[u] == dfn[u])
    {
        Bcnt ++;
        int v;
        do
        {
            v = stack[Scnt --];
            belong[v] = Bcnt;
            instack[v] = false;
        }while(v != u);
    }
}

int main()
{
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; ++i)
        head[i] = -1;
    label = -1;
    for (int i = 1; i <= m; ++i)
    {
        int u, v;
        scanf("%d %d", &u, &v);
        ins(u, v);
    }
    for (int i = 1; i <= n; ++i)
        instack[i] = belong[i] = dfn[i] = 0;
    Scnt = Bcnt = dfs_clock = 0;
    for (int i = 1; i <= n; ++i)
        if (!dfn[i])
            dfs(i);
    for (int i = 1; i <= Bcnt; ++i)
        siz[i] = chu[i] = 0;
    for (int i = 1; i <= n; ++i)
    {
        siz[belong[i]] ++;
        for (int j = head[i]; j != -1; j = e[j].next)
        {
            int v = e[j].v;
            if (belong[v] == belong[i])
                continue ;
            chu[belong[i]] ++;
        }
    }
    int cnt = 0, ans;
    for (int i = 1; i <= Bcnt; ++i)
        if (chu[i] == 0)
            cnt ++, ans = siz[i];
    if (cnt > 1)
        ans = 0;
    printf("%d\n", ans);
    return 0;
}

 

posted @ 2017-02-17 22:03  Splay  阅读(252)  评论(0编辑  收藏  举报