• 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
    ",ANS);
    	return 0;
    }
    
  • 相关阅读:
    远程连接桌面报:这可能是由于credssp加密oracle修正
    MVC断点续传
    [COCI2011-2012#5] POPLOCAVANJE 后缀自动机
    [SDOI2016]生成魔咒 后缀自动机
    [JSOI2009]密码 AC自动机
    CF17E Palisection manacher
    [JSOI2007]字符加密 后缀数组
    [POI2012]OKR-A Horrible Poem hash
    [APIO2014]回文串 manacher 后缀数组
    [SHOI2011]双倍回文 manacher
  • 原文地址:https://www.cnblogs.com/MyNameIsPc/p/9424834.html
Copyright © 2020-2023  润新知