#53643: 影片講解 並非最速解但一般使用足以


tryit163281@gmail.com (CodingBarJoe(被逼著不得不刷題=_=))

學校 : 不指定學校
編號 : 74499
來源 : [210.68.224.131]
最後登入時間 :
2025-09-30 15:45:58

https://youtu.be/2m1BlJCg95k

#include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> children[100005];  // 每個節點的子節點列表
bool has_parent[100005];       // 標記節點是否有父節點
long long total_height;        // H(T) = 所有節點高度總和

// 計算以 node 為根的子樹高度,並累加到總高度
int dfs(int node) {
    if (children[node].empty()) {// 葉子節點高度為 0
        return 0;
    }
    int max_height = 0;
    for (int child : children[node]) {
        int child_height = dfs(child);
        max_height = max(max_height, child_height);
    }
    //節點高度 = 最高子樹高度 + 1
    int node_height = max_height + 1;
    total_height += node_height;
    return node_height;
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n;//總共有多少節點
    for (int i = 1; i <= n; i++) {//初始化,把用得上的clean掉即可
        children[i].clear();
        has_parent[i] = 0;
    }
    total_height = 0;
    //讀入樹的結構
    for (int i = 1; i <= n; i++) {
        int k;
        cin >> k;
        for (int j = 0; j < k; j++) {
            int child;
            cin >> child;
            children[i].push_back(child);
            has_parent[child] = 1;  //child 有父節點
        }
    }
    //找根節點並計算所有節點高度
    for (int i = 1; i <= n; i++) {
        if (!has_parent[i]) {//找到根節點,開始DFS計算高度
            dfs(i);
            cout << i << "\n" << total_height << "\n";
            break;
        }
    }
    
    return 0;
}