题解:P16428 「YLLOI-R4-T4」稻香

· · 题解

只能部分正确,希望对你有帮助


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const int MAXN = 1e5 + 5;

int lson[MAXN], rson[MAXN];
int riceora;  // 题目要求必须定义的变量
char opt;
int n, root, k;
vector<int> res;

// 获取子树遍历的第一个元素(决定字典序)
int get_first(int u) {
    if (u == 0) return 1e9;
    if (opt == 'A') {  // 前序:根最先
        return u;
    }
    if (opt == 'B') {  // 中序:左子树第一个
        return get_first(lson[u]);
    }
    if (opt == 'C') {  // 后序:左子树第一个
        return get_first(lson[u]);
    }
    return 1e9;
}

// 递归处理:交换并生成遍历序列
void dfs(int u) {
    if (u == 0) return;

    int L = lson[u];
    int R = rson[u];

    // 满二叉树:非叶子一定有两个儿子
    if (L != 0 && R != 0 && k > 0) {
        int lf = get_first(L);
        int rf = get_first(R);
        // 右子树更小,交换(消耗1次次数)
        if (rf < lf) {
            swap(lson[u], rson[u]);
            k--;
        }
    }

    // 生成对应遍历序列
    if (opt == 'A') {  // 前序:根 -> 左 -> 右
        res.push_back(u);
        dfs(lson[u]);
        dfs(rson[u]);
    } else if (opt == 'B') {  // 中序:左 -> 根 -> 右
        dfs(lson[u]);
        res.push_back(u);
        dfs(rson[u]);
    } else if (opt == 'C') {  // 后序:左 -> 右 -> 根
        dfs(lson[u]);
        dfs(rson[u]);
        res.push_back(u);
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> opt;
    cin >> n >> root >> k;

    for (int i = 1; i <= n; i++) {
        cin >> lson[i] >> rson[i];
    }

    dfs(root);

    // 输出答案
    for (int x : res) {
        cout << x << " ";
    }
    cout << endl;

    return 0;
}