# Ian 問題 ```cpp= #include <iostream> #include <vector> #include <queue> using namespace std; int main() { int n; cin >> n; vector<int> parent(n); // 設定所有節點的父節點 for (int i = 0; i < n; ++i) { cin >> parent[i]; } // 根據題目說明值 -1 為根節點 int root = -1; for (int i = 0; i < n; ++i) { if (parent[i] == -1) { root = i; break; } } // 使用一個 queue 來進行 BFS queue<int> q; q.push(root); int height = 0; while (!q.empty()) { // 當前階層的節點數量 int level_size = q.size(); // 走訪當前階層的每一個節點 for (int i = 0; i < level_size; ++i) { // 取出 queue 最前面的節點,並設定為當前節點 int currentNode = q.front(); // 將剛取出的節點從 queue 中移除以免重複計算 q.pop(); // 將當前節點的所有子節點放入 queue for (int j = 0; j < n; ++j) { // 如果某節點的父節點為當前節點就要將它放到 queue 中 if (parent[j] == currentNode) { q.push(j); } } } // 當走訪完當前階層的所有節點,就代表高度又上升了 ++height; } cout << height << endl; return 0; } ```