D17 Tarjan 割边
视频链接:https://www.bilibili.com/video/BV14g411Q7ze
// Luogu P1656 炸铁路(可处理重边) // 链式邻接表 #include <cstring> #include <iostream> #include <algorithm> #include <vector> using namespace std; const int N=210,M=10010; int n,m,a,b,cnt; struct edge{int u,v;}; vector<edge>e; vector<int>h[N]; int dfn[N],low[N],tot; struct bridge{ int x,y; bool operator<(const bridge &t)const{ if(x==t.x)return y<t.y; return x<t.x; } }bri[M]; void add(int a,int b){ e.push_back({a,b}); h[a].push_back(e.size()-1); } void tarjan(int x,int in_edge){ dfn[x]=low[x]=++tot; for(int i=0;i<h[x].size();i++){ int j=h[x][i], y=e[j].v; if(!dfn[y]){//若y尚未访问 tarjan(y,j); low[x]=min(low[x],low[y]); if(low[y]>dfn[x]){ bri[cnt++]={x,y}; } } else if(j!=(in_edge^1))//不是反边 low[x]=min(low[x],dfn[y]); } } int main(){ cin>>n>>m; while(m --){ cin>>a>>b; add(a,b),add(b,a); } for(int i=1; i<=n; i++) if(!dfn[i])tarjan(i,0); sort(bri,bri+cnt); for(int i=0;i<cnt;i++) printf("%d %d\n",bri[i].x,bri[i].y); return 0; } // Luogu P1656 炸铁路(可处理重边) // 链式前向星 #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N=210,M=10010; int n,m,a,b,cnt; struct edge{int v,ne;}e[M]; int h[N],idx=1;//从2,3开始配对 int dfn[N],low[N],tot; struct bridge{ int x,y; bool operator<(const bridge &t)const{ if(x==t.x)return y<t.y; return x<t.x; } }bri[M]; void add(int a,int b){ e[++idx]={b,h[a]}; h[a]=idx; } void tarjan(int x,int in_edge){ dfn[x]=low[x]=++tot; for(int i=h[x];i;i=e[i].ne){ int y=e[i].v; if(!dfn[y]){//若y尚未访问 tarjan(y,i); low[x]=min(low[x],low[y]); if(low[y]>dfn[x]){ bri[cnt++]={x,y}; } } else if(i!=(in_edge^1))//不是反边 low[x]=min(low[x],dfn[y]); } } int main(){ cin>>n>>m; while(m --){ cin>>a>>b; add(a,b),add(b,a); } for(int i=1; i<=n; i++) if(!dfn[i])tarjan(i,0); sort(bri,bri+cnt); for(int i=0;i<cnt;i++) printf("%d %d\n",bri[i].x,bri[i].y); return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验