POJ 1523 SPF tarjan求割点模板

本文介绍了一种求解无向图中割点及其移除后形成的联通块数量的算法。通过Tarjan算法进行深度优先搜索,实现对割点的识别,并统计移除割点后图的连通性。

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

时空隧道


说起来真是惭愧QAQ…
现在刚会求割点QAQ…


题意:
给出一张无向图,求出割点以及去掉割点之后原图分成了几个联通块


代码如下:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
//by NeighThorn
#define Max(a,b,c) max(a,max(b,c))
using namespace std;
//天上夭桃盛,云中杏蕊多 
const int maxn=1000+5,maxm=maxn*maxn*2+5;
int cas,n,hd[maxn],to[maxm],nxt[maxm],cnt,dfn[maxn],low[maxn],stk[maxn],tail,instk[maxn],tim,vis[maxn];

inline void add(int x,int y){
    to[cnt]=y;
    nxt[cnt]=hd[x];
    hd[x]=cnt++;
}

inline void tarjan(int root){
    dfn[root]=low[root]=++tim;stk[++tail]=root;instk[root]=1;vis[root]=1;
    for(int i=hd[root];i!=-1;i=nxt[i]){
        if(!vis[to[i]]){
            tarjan(to[i]);low[root]=min(low[root],low[to[i]]);
            if(dfn[root]<=low[to[i]])
                vis[root]++;
        }
        else low[root]=min(low[root],dfn[to[i]]);   
    }
}


signed main(void){
    int x,y;cas=0;
    while(scanf("%d",&x)&&x){
        n=0;cnt=tail=0;
        memset(hd,-1,sizeof(hd));
        memset(dfn,0,sizeof(dfn));
        memset(low,0,sizeof(low));
        memset(vis,0,sizeof(vis));
        scanf("%d",&y),add(x,y),add(y,x);n=Max(x,y,n);
        while(scanf("%d",&x)&&x)
            scanf("%d",&y),add(x,y),add(y,x),n=Max(x,y,n);
        printf("Network #%d\n",++cas);tarjan(1);int flag=0;
        for(int i=1;i<=n;i++)
            if((i==1&&vis[i]>2)||(i>1&&vis[i]>1))
                flag=1,printf("  SPF node %d leaves %d subnets\n",i,i==1?vis[i]-1:vis[i]);
        if(!flag)
            puts("  No SPF nodes");
        puts("");
    }
    return 0;
}

by >_< NeighThorn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值