C ++程序查找图形中的铰接点数
图中的铰接点(或切点)是将其移除(以及通过它的边)会断开图的连接的点。断开的无向图的连接点是顶点移除,这增加了连接的组件数。
算法
Begin We use dfs here to find articulation point: In DFS, a vertex w is articulation point if one of the following two conditions is satisfied. 1) w is root of DFS tree and it has at least two children. 2) w is not root of DFS tree and it has a child x such that no vertex in subtree rooted with w has a back edge to one of the ancestors of w in the tree. End
示例
#include<iostream> #include <list> #define N -1 using namespace std; class G { int n; list<int> *adj; //功能声明 void APT(int v, bool visited[], int dis[], int low[], int par[], bool ap[]); public: G(int n); //constructor void addEd(int w, int x); void AP(); }; G::G(int n) { this->n = n; adj = new list<int>[n]; } //在图上添加边 void G::addEd(int w, int x) { adj[x].push_back(w); //add u to v's list adj[w].push_back(x); //add v to u's list } void G::APT(int w, bool visited[], int dis[], int low[], int par[], bool ap[]) { static int t=0; int child = 0; //initialize child count of dfs tree is 0. //将当前节点标记为已访问 visited[w] = true; dis[w] = low[w] = ++t; list<int>::iterator i; //遍历所有相邻的顶点 for (i = adj[w].begin(); i != adj[w].end(); ++i) { int x = *i; //x is current adjacent if (!visited[x]) { child++; par[x] = w; APT(x, visited, dis, low, par, ap); low[w] = min(low[w], low[x]); //w在以下情况下是一个关节点: //w是DFS树的根,具有两个或多个孩子。 if (par[w] == N && child> 1) ap[w] = true; //如果w不是根,并且其子级之一的低值大于w的发现值。 if (par[w] != N && low[x] >= dis[w]) ap[w] = true; } else if (x != par[w]) //update low value low[w] = min(low[w], dis[x]); } } void G::AP() { //将所有顶点标记为未访问 bool *visited = new bool[n]; int *dis = new int[n]; int *low = new int[n]; int *par = new int[n]; bool *ap = new bool[n]; for (int i = 0; i < n; i++) { par[i] = N; visited[i] = false; ap[i] = false; } // Call the APT() function to find articulation points in DFS tree rooted with vertex 'i' for (int i = 0; i < n; i++) if (visited[i] == false) APT(i, visited, dis, low, par, ap); //打印发音点 for (int i = 0; i < n; i++) if (ap[i] == true) cout << i << " "; } int main() { cout << "\nArticulation points in first graph \n"; G g1(5); g1.addEd(1, 2); g1.addEd(3, 1); g1.addEd(0, 2); g1.addEd(2, 3); g1.addEd(0, 4); g1.AP(); return 0; }
输出结果
Articulation points in first graph 0 2