强连通分量缩点 POJ 2186

本文介绍了一种使用Tarjan算法实现的强连通分量(SCC)计算方法,针对给定的无向图,通过深度优先搜索和低点标号找出所有强连通组件,并应用在计算社区结构中。关键步骤包括tarjan函数的递归调用和belong数组的更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1<<30;
const LL maxn = 50010;

int N, M, ecnt = 1, head[maxn];
struct node{
    int v, next;
}es[maxn];
void addEdge(int u, int v){
    es[ecnt].v = v, es[ecnt].next = head[u];
    head[u] = ecnt++;
}
int indx = 0, scc = 0;
bool ins[maxn];
int dfn[maxn], low[maxn], belong[maxn];
stack<int> s;
void tarjan(int u){
    int v;
    dfn[u] = low[u] = ++indx;
    s.push(u);
    ins[u] = true;
    for(int i = head[u]; i != -1; i = es[i].next){
        v = es[i].v;
        if(!dfn[v]){
            tarjan(v);
            low[u] = min(low[u], low[v]);
        }
        else if(ins[v])
            low[u] = min(low[u], dfn[v]);
    }
    if(dfn[u] == low[u]){
        ++scc;
        do{
            v = s.top();
            s.pop();
            ins[v] = false;
            belong[v] = scc;
        }while(u!=v);
    }
}
int out[maxn], in[maxn];
int main()
{
    int a, b;
    ms(head, -1);
    cin >> N >> M;
    for(int i = 1; i <= M; ++i){
        cin >> a >> b;
        addEdge(a, b);
    }
    for(int i = 1; i <= N; ++i){
        if(!dfn[i])
            tarjan(i);
    }

    for(int u = 1; u <= N; ++u){
        for(int i = head[u]; i != -1; i = es[i].next){
            int v = es[i].v;
            if(belong[u] != belong[v])
                ++out[belong[u]], ++in[belong[u]];
        }
    }
    int cnt = 0, ans = 0, tag;
    for(int i = 1; i <= scc; ++i)
        if(out[i]==0)
            ++cnt, tag = i;
    if(cnt!=1) cout << "0" << endl;
    else{
        for(int i = 1; i <= N; ++i)
            if(belong[i] == tag)
                ++ans;
        cout << ans << endl;;
    }

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值