标签:www. 技术 r++ int int() target class 输出 nbsp
题目:输出深度优先生成树
/* 数据结构:邻接表存储图 程序说明:为简单起见,设节点的类型为整型,设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) } } }
运行结果:
标签:www. 技术 r++ int int() target class 输出 nbsp
原文地址:https://www.cnblogs.com/sunbines/p/8870065.html