POI2011 Tree Rotations

POI2011 Tree Rotations

给定一个n<=2e5个叶子的二叉树,可以交换每个点的左右子树。要求前序遍历叶子的逆序对最少。

由于对于当前结点x,交换左右子树,对于范围之外的逆序对个数并没有影响,所以可以进行线段树合并,合并时统计l在左边还是在右边更优。

#include <cstdio>
#include <cctype>
using namespace std;
typedef long long LL;

inline void read(int &x){
    char ch; x=0;
    for (; ch=getchar(), !isdigit(ch););
    for (x=ch-48; ch=getchar(), isdigit(ch);)
        x=(x<<3)+(x<<1)+ch-48;
}
inline void read(LL &x){
    char ch; x=0;
    for (; ch=getchar(), !isdigit(ch););
    for (x=ch-48; ch=getchar(), isdigit(ch);)
        x=(x<<3)+(x<<1)+ch-48;
}
inline LL min(LL a,LL b) { return a > b?b : a; }

const int maxn = 2e5+5;
struct node {
    int seg,ls,rs;
} a[maxn*30];
LL ANS = 0,ans1 = 0,ans2 = 0;
int n;

int cnt = 0;
void modify(int &x,int l,int r, int pos) {
    if(!x) x = ++cnt;
    a[x].seg++;
    int mid=l+r>>1;
    if(l == r) return;
    if(pos <= mid) modify(a[x].ls,l,mid,pos);
    else modify(a[x].rs,mid+1,r,pos);
}
void merge(int &l,int r) {
    if(!l || !r) { l+=r; return; }
    a[l].seg += a[r].seg;
    ans1 += (LL)a[a[l].rs].seg*a[a[r].ls].seg;
    ans2 += (LL)a[a[l].ls].seg*a[a[r].rs].seg;
    merge(a[l].ls,a[r].ls);
    merge(a[l].rs,a[r].rs);
}

void solve(int &x) {
    int t,ls,rs;
    x = 0; read(t);
    if(!t) {
        solve(ls),solve(rs);
        ans1 = ans2 = 0;
        x = ls;
        merge(x,rs);
        ANS += min(ans1,ans2);
    } else modify(x,1,n,t);
}

int main() {
    read(n);
    int t = 0;
    solve(t);
    printf("%lld\n",ANS);
    return 0;
}

转载于:https://www.cnblogs.com/MyNameIsPc/p/9424834.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值