1 条题解

  • 0
    @ 2026-11-2 13:31:44

    左孩子右兄弟(Left-Child Right-Sibling) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        if (!(cin >> n)) return 0;
        vector<int> p(n + 1, 0), cnt(n + 1, 0), maxChild(n + 1, 0), dp(n + 1, 0);
        for (int i = 2; i <= n; ++i) {
            cin >> p[i];
            cnt[p[i]]++;
        }
        for (int i = n; i >= 1; --i) {
            dp[i] = cnt[i] + maxChild[i];
            if (p[i] > 0) {
                maxChild[p[i]] = max(maxChild[p[i]], dp[i]);
            }
        }
        cout << dp[1] << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8694
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者