1. 程式人生 > 其它 >演算法作業 - 最小半徑的生成樹

演算法作業 - 最小半徑的生成樹

技術標籤:演算法作業演算法

題目描述:
在這裡插入圖片描述
解析:這道題要求半徑最小,根據題目描述其實也就是高度最小,只需要用b遍歷以每個節點為根節點的生成樹,找到其中高度最小的就行了。

程式碼:

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define MAX 101
using namespace std;

void DFS(vector<vector<int>>matrix, int i, int n, int height,
int &maxHeight) { if (height > maxHeight)maxHeight = height; vector<int>point; for (auto j = 0; j < n; j++) { if (matrix[i][j] == 1) { matrix[i][j] = 0; matrix[j][i] = 0; point.push_back(j); } } for(auto j = 0; j < point.size(); j++) DFS(matrix, point[j], n, height +
1, maxHeight); } int main() { int n, e; cout << "輸入節點數和邊數:" << endl; cin >> n >> e; cout << "輸入各條邊:" << endl; int start, end, value; vector<vector<int>>matrix; for (auto i = 0; i < n; i++) { vector<int>p(n, 0); matrix.
push_back(p); } for (auto i = 0; i < e; i++) { cin >> start >> end; matrix[start][end] = 1; matrix[end][start] = 1; } int minHeight = INT_MAX; for (auto i = 0; i < n; i++) { int maxHeight = -1; DFS(matrix, i, n, 0, maxHeight); if (minHeight > maxHeight)minHeight = maxHeight; } cout << minHeight << endl; return 0; }