1. 程式人生 > >【圖:C++】 深度優生成樹

【圖:C++】 深度優生成樹

pri 打印 割點 圖片 mes 全局變量 num 運行 push

傳送門

題目:輸出深度優先生成樹
技術分享圖片

/*
數據結構:鄰接表存儲圖
程序說明:為簡單起見,設節點的類型為整型,設visited[],num[].low[],parent[]為全局變量,
為求得先序編號num[],設置全局變量counter並初始化為1。為便於單獨處理根節點設置root變量。
*/
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const int MAX_N = 100;
vector<int> graph[MAX_N];
vector
<int> artPoint; int num[MAX_N], low[MAX_N], parent[MAX_N]; int counter = 1; int root; bool visited[MAX_N]; void Init(); //初始化圖 void FindArt(int v); //找到第二類割點 void PrintArtPoint(); //打印所有割點(第一類割點在此單獨處理) int main() { Init(); FindArt(root); PrintArtPoint();
return 0; } void PrintArtPoint() { int rootChild = 0; //根節點的孩子個數 for (int i = 0; i < graph[root].size(); i++) //計算根節點的孩子個數 { if (parent[graph[root][i]] == root) rootChild++; } if (rootChild > 1) //根節點孩子個數大於1則為割點 artPoint.push_back(root);
for (int i = 0; i < artPoint.size(); i++) printf("%d\n", artPoint[i]); } void Init() { int a, b; root = 1; while (scanf("%d%d", &a, &b) != EOF) { graph[a].push_back(b); graph[b].push_back(a); visited[a] = false; visited[b] = false; } } void FindArt(int v) { visited[v] = true; low[v] = num[v] = counter++; //情況(1) for (int i = 0; i < graph[v].size(); i++) { int w = graph[v][i]; if (!visited[w]) //樹邊 { parent[w] = v; FindArt(w); if (low[w] >= num[v] && v != root) artPoint.push_back(v); low[v] = min(low[v], low[w]); //情況(3) } else if (parent[v] != w) //回退邊 { low[v] = min(low[v], num[w]); //情況(2) } } }

運行結果:

【圖:C++】 深度優生成樹