[POI2011]ROT-Tree Rotations

本文介绍了一个关于二叉树的问题,通过贪心算法实现子树逆序对的最小化,采用线段树进行高效计算。文章提供了完整的代码实现及解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目链接】
洛谷 P3521
BZOJ 2212

【解析】
贪心,使一个非叶子结点的两棵子树前序遍历逆序对最少,得出的便是最优解。
证明:
因为交换一个非叶子结点的两棵子树,对该子树内叶子结点与子树外结点组成的逆序对个数无影响,所以局部最优解就是最优解。
将二叉树上的每个结点的子树情况用一棵权值线段树表示,每次合并即可。

【代码】

#include<cstdio>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
void read(int &x) {
    char c = getchar(); x = 0;
    while (!isdigit(c)) c = getchar();
    while (isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); }
}
const int N = 4e5 + 10;
const int M = 4e6 + 10;
int n;
struct node_ { // 二叉树结点
    int w, lc, rc;
} a[N];
int root_, cnt_; // 二叉树相关
void build(int &o) {
    o = ++cnt_;
    read(a[o].w);
    if (a[o].w) return;
    build(a[o].lc);
    build(a[o].rc);
}
struct node { // 线段树结点
    int size, lc, rc;
} s[M];
int root[N], cnt;
LL cnt1, cnt2, ans;
inline void push_up(int o) {
    s[o].size = s[s[o].lc].size + s[s[o].rc].size;
}
void ins(int &o, int l, int r, int x) {
    if (!o) o = ++cnt;
    s[o].size++;
    if (l == r) return;
    int mid = (l + r) >> 1;
    if (x <= mid) ins(s[o].lc, l, mid, x);
    else ins(s[o].rc, mid + 1, r, x);
}
int merge(int x, int y) {
    if (!x || !y) return x | y;
    cnt1 += (LL) s[s[x].rc].size * s[s[y].lc].size;
    cnt2 += (LL) s[s[x].lc].size * s[s[y].rc].size;
    s[x].lc = merge(s[x].lc, s[y].lc);
    s[x].rc = merge(s[x].rc, s[y].rc);
    push_up(x);
    return x;
}
void solve(int o) {
    if (!o) return;
    int lc = a[o].lc, rc = a[o].rc;
    solve(lc), solve(rc);
    if (!a[o].w) {
        cnt1 = cnt2 = 0;
        root[o] = merge(root[lc], root[rc]);
        ans += min(cnt1, cnt2);
    }
}
int main() {
    read(n);
    build(root_);
    for (int i = 1; i <= cnt_; i++) if (a[i].w) ins(root[i], 1, n, a[i].w);
    solve(root_);
    cout << ans;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值