無向圖的割點和橋
阿新 • • 發佈:2019-01-29
割點(割頂):無向連通圖中,刪除某點後,圖變成不連通,稱該點為割點;
橋:無向連通圖中,如果刪除某條邊後,圖變成不連通,則該邊稱為橋;
定理:在無向連通圖的dfs樹中,非根節點u是割點當且僅當u存在一個子節點v使得v及其所有後代都沒有反向邊連回u的祖先(連回u不算)
求割點的Tarjan演算法:
求無向圖的橋演算法:#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<climits> #include<cctype> #include<iostream> #include<algorithm> #include<queue> #include<vector> #include<map> #include<set> #include<stack> #include<string> #define ll long long #define MAX 1000 #define INF INT_MAX #define eps 1e-8 using namespace std; int pre[MAX],mark[MAX],low[MAX],dfs_clock; //mark[i]用來標記節點是否為割點 vector<int>G[MAX]; int n; void init(){ for (int i=0; i<=n; i++) G[i].clear(); memset(pre,0,sizeof(pre)); memset(mark,0,sizeof(mark)); dfs_clock = 0; } int dfs(int u, int fa){ int lowu = pre[u] = ++dfs_clock; int c = 0; for (int i=0; i<G[u].size(); i++){ int v = G[u][i]; if (!pre[v]){ c++; int lowv = dfs(v,u); lowu = min(lowu,lowv); if (lowv >= pre[u]){ //判斷節點u是不是存在一子節點v,使得v以及其所有後代都沒有反邊連回u的祖先 mark[u] = 1; } } else if (pre[v] < pre[u] && v != fa){ //注意不再考慮連到父親節點的回邊; lowu = min(lowu,pre[v]); } } if (fa < 0 && c == 1) mark[u] = 0; //當且僅當根節點有多個孩子節點時才是割點 low[u] = lowu; return lowu; } int main(){ int m; while(scanf("%d%d",&n,&m) != EOF){ init(); int u,v; for (int i=0; i<m; i++){ scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } dfs(1,-1); for (int i=1; i<=n; i++) if (mark[i]) printf("%d ",i); printf("\n"); } return 0; }
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<climits> #include<cctype> #include<iostream> #include<algorithm> #include<queue> #include<vector> #include<map> #include<set> #include<stack> #include<string> #define ll long long #define MAX 1000 #define INF INT_MAX #define eps 1e-8 using namespace std; struct Edge{ int u, v; }; int pre[MAX],low[MAX],dfs_clock; vector<int>G[MAX]; vector<Edge> edges; //記錄橋 int n; void init(){ for (int i=0; i<=n; i++) G[i].clear(); edges.clear(); memset(pre,0,sizeof(pre)); dfs_clock = 0; } int dfs(int u, int fa){ int lowu = pre[u] = ++dfs_clock; int c = 0; for (int i=0; i<G[u].size(); i++){ int v = G[u][i]; if (!pre[v]){ c++; int lowv = dfs(v,u); lowu = min(lowu,lowv); if (lowv > pre[u]){ //注意和割點的區別,對於u的子節點v,v的後代只能連回自己,則(u,v)為橋 edges.push_back((Edge){u,v}); } } else if (pre[v] < pre[u] && v != fa){ lowu = min(lowu,pre[v]); } } low[u] = lowu; return lowu; } int main(){ int m; while(scanf("%d%d",&n,&m) != EOF){ init(); int u,v; for (int i=0; i<m; i++){ scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } dfs(1,-1); for (int i=0; i<edges.size(); i++){ printf("%d %d\n",edges[i].u,edges[i].v); } } return 0; }