zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    Python合集之Python字典(一)
    Python合集之Python元组(三)
    Python合集之Python元组(二)
    Python合集之Python元组(一)
    Python合集之Python列表(七)
    Python合集之Python列表(六)
    Python合集之Python列表(五)
    Python合集之Python列表(四)
    Python合集之Python列表(三)
    对《软件工程》课程的总结
  • 原文地址:https://www.cnblogs.com/MyNameIsPc/p/9424834.html
Copyright © 2011-2022 走看看