【图论】tarjan求割点和桥(无向双联通)

本文介绍了使用Tarjan算法求解无向图中的割点和桥。通过邻接表实现,算法的时间复杂度为O(n+m)。文章提供了求解割点和桥的模板代码,并提及了无向图的边双联通缩点问题。

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

参考:https://blog.youkuaiyun.com/wtyvhreal/article/details/43530613
因为我是用邻接表写的,所以时间复杂度:O(n+m);
求割点模板:
(前向星):

#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
#define IO ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=2e5+10;
ll root;
ll dfn[maxn],low[maxn],tott,n,m,ans=-1,vis[maxn],flag[maxn];
stack<ll> s;
ll tot;ll head[maxn];ll fa[maxn];
struct E{
   
	ll to,next;
}edge[maxn<<1];
void add(ll u,ll v){
   
	edge[tot].to=v;
	edge[tot].next=head[u];
	head[u]=tot++;
}
void tarjan(ll x){
   
	ll child=0;
	low[x]=dfn[x]=++tott;
	for(ll i=head[x];i!=-1;i=edge[i].next){
   
		ll v=edge[i].to;
		if(!dfn[v]){
   
			child++;fa[v]=x;
			tarjan(v);
			low[x]=min(low[x],low[v]);
			if(fa[x]!=-1&&low[v]>=dfn[x]) flag[x]=1;
			if(fa[x]==-1&&child>=2) flag[x]=1;
		}else if(v!=fa[x]
### Tarjan算法解图中的方法 #### 方法介绍 Tarjan算法是一种基于深度优先搜索(DFS)的高效方法,用于解决图论中的多种问题,其中包括寻找无向图中的是指在一个连通图中删除该节及其相连的所有边之后,使得原本连通的部分变得不连通的节。 在Tarjan算法中,通过维护两个数组 `dfn` `low` 来辅助判断某个节是否为: - **`dfn[u]`**: 表示节 `u` 被访问的时间顺序。 - **`low[u]`**: 表示从节 `u` 或其后代出发能回溯到的最早祖先节的时间戳[^3]。 对于根节以外的任意节 `u`,如果存在至少一个子节 `v` 满足条件 `low[v] >= dfn[u]`,则说明删除节 `u` 后无法再通过任何路径到达子树内的某些节,因此 `u` 是[^1]。 另外需要注意的是,当处理根节时,只有在其具有超过一个子树的情况下才被认为是[^4]。 #### 代码实现 以下是使用 C++ 编写的 Tarjan 算法来查找无向图中所有的一个具体例子: ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 10005; vector<int> G[MAXN]; bool vis[MAXN]; // 访问标记 int dfn[MAXN], low[MAXN], cnt_time; // 时间戳计数器 bool isCutPoint[MAXN]; // 是否为标志位 int root, childCount; // 当前正在遍历的根节及它的孩子数量统计 void tarjan(int u){ dfn[u] = low[u] = ++cnt_time; vis[u] = true; int children = 0; for(auto v : G[u]){ if(!vis[v]){ // 如果未被访问过,则继续向下探索 children++; tarjan(v); low[u] = min(low[u], low[v]); if(u != root && low[v] >= dfn[u]) isCutPoint[u] = true; if(u == root) childCount = children; } else{ low[u] = min(low[u], dfn[v]); } } } int main(){ ios::sync_with_stdio(false); cin.tie(0); int n,m,u,v; cin>>n>>m; while(m--){ cin >> u >> v; G[u].push_back(v); G[v].push_back(u); } memset(vis,false,sizeof(vis)); memset(isCutPoint,false,sizeof(isCutPoint)); for(int i=1;i<=n;i++){ if(!vis[i]){ root=i; childCount=0; tarjan(i); if(childCount >1) isCutPoint[root]=true; } } vector<int> res; for(int i=1;i<=n;i++) if(isCutPoint[i]) res.push_back(i); cout << "Cut Points are:\n"; for(auto p:res) cout<<p<<" "; } ``` 此程序首先读取输入构建邻接表表示的无向图,接着调用 `tarjan()` 函数执行 DFS 遍历来识别所有的,并最终打印出来这些的结果列表^。 ### 结果解释 上述代码会输出给定无向图中的全部集合。它利用了 Tarjan 的核心思想——即通过比较各顶与其子孙们之间的最低可达时间戳 (`low`) 值同当前顶首次发现时刻(`dfn`)的关系来进行判定操作[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值