全部评论 1

  • #include <bits/stdc++.h>
    using namespace std;
    const int MAXN = 2e5 + 10;
    vector<int> adj[MAXN];
    int a[MAXN], n;
    bool cmp(int x, int y) {
    if (a[x] != a[y]) return a[x] < a[y];
    // 双指针遍历孩子列表,比较字典序
    auto &vx = adj[x], &vy = adj[y];
    int i = 0, j = 0, sx = vx.size(), sy = vy.size();
    while (i < sx && j < sy) {
    if (cmp(vx[i], vy[j])) return true;
    if (cmp(vy[j], vx[i])) return false;
    i++, j++;
    }
    return sx < sy;
    }
    void dfs_sort(int u, int fa) {
    vector<int> sons;
    for (int v : adj[u]) {
    if (v != fa) {
    dfs_sort(v, u);
    sons.push_back(v);
    }
    }
    sort(sons.begin(), sons.end(), cmp);
    adj[u] = move(sons);
    }
    void dfs_print(int u) {
    cout << a[u] << ' ';
    for (int v : adj[u]) {
    dfs_print(v);
    }
    }
    int main() {
    cin >> n;
    for (int i = 1; i <= n; ++i)cin >> a[i];
    for (int i = 1; i < n; ++i) {
    int u, v;
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
    }
    dfs_sort(1, -1);
    dfs_print(1);
    return 0;
    }我47行就搞定了<->

    昨天 来自 浙江

    0
暂无数据

提交答案之后,这里将显示提交结果~

首页