題目大意:給一張無向圖,現在要去掉一些邊,使圖仍然連通,求不能去掉的邊。 題目分析:就是求無向圖的橋。 tarjan算法跑一遍,和無向圖割點十分類似,這裡要找low[v] > dfn[u]的邊(u,v)便是割邊,因為v是u的孩子,但是v無法訪問到u的祖先,那麼斷開這條邊原圖必不連通,因此這是橋。這題會有平行邊,平行邊必定不是橋。所以dfs的時候要判斷一下。 詳情請見代碼:
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 10005; const int M = 500005; int m,n,num,ansnum,dfns; int head[N],ans[M],low[N],dfn[N]; bool vis[N]; struct node { int to,next,id; }bridge[M<<1]; void build(int s,int e,int id) { bridge[num].id = id; bridge[num].to = e; bridge[num].next = head[s]; head[s] = num ++; } void dfs(int cur,int fa) { vis[cur] = true; int chongbian = 0; dfn[cur] = low[cur] = dfns ++; for(int i = head[cur];i != -1;i = bridge[i].next) { if(fa == bridge[i].to) chongbian ++; if(vis[bridge[i].to] == false) { dfs(bridge[i].to,cur); low[cur] = min(low[cur],low[bridge[i].to]); if(low[bridge[i].to] > dfn[cur]) ans[ansnum ++] = bridge[i].id; } else if(fa != bridge[i].to || chongbian > 1) low[cur] = min(low[cur],dfn[bridge[i].to]); } } void tarjan() { int i; dfns = 1; memset(vis,false,sizeof(vis)); memset(dfn,0,sizeof(dfn)); for(i = 1;i <= n;i ++) if(vis[i] == false) dfs(i,-1); printf("%d\n",ansnum); sort(ans,ans + ansnum); for(i = 0;i < ansnum;i ++) printf(i == ansnum - 1?"%d\n":"%d ",ans[i]); } int main() { int t,i; int a,b; scanf("%d",&t); while(t --) { scanf("%d%d",&n,&m); memset(head,-1,sizeof(head)); num = ansnum = 0; for(i = 1;i <= m;i ++) { scanf("%d%d",&a,&b); build(a,b,i); build(b,a,i); } tarjan(); if(t) puts(""); } return 0; }