LP3521 [POI2011]ROT-Tree Rotations

Problem

https://www.luogu.org/problemnew/show/P3521

Solution

这玩意怎么这么像我考过的一道...

现在想想我那东西好像不太好用这东西优化emm

这边就是计算左右子树互相贡献的最小值之和就行了

也是我第一次打线段树合并纪念一下emm

Code

// Code by ajcxsu
// Problem: ROT

#include<bits/stdc++.h>
using namespace std;

struct Node *nil; 
struct Node {
    int val;
    Node *ls, *rs;
    Node(int v=0):val(v) { ls=rs=nil; }
} ;
void ini() { nil=new Node(), nil->ls=nil->rs=nil; }

void updata(Node *&x, int l, int r, int d) {
    Node *nd=new Node(); *nd=*x, x=nd, x->val++;
    if(l==r) return;
    int mid=(l+r)>>1;
    if(d<=mid) updata(x->ls, l, mid, d);
    else updata(x->rs, mid+1, r, d);
}
typedef long long ll;
ll na, nb;
void Merge(Node *&x, Node *a, Node *b, int l, int r) {
    if(a==nil) { x=b; return; }
    if(b==nil) { x=a; return; }
    Node *nd=new Node(); *nd=*x, x=nd, x->val=a->val+b->val;
    na+=1ll*a->rs->val*b->ls->val, nb+=1ll*b->rs->val*a->ls->val; 
    int mid=(l+r)>>1;
    Merge(x->ls, a->ls, b->ls, l, mid);
    Merge(x->rs, a->rs, b->rs, mid+1, r);
    delete a;
    delete b;
}

int n;
ll ans;
Node *dfs() {
    Node *ln, *rn, *ret=nil;
    int x;
    cin>>x;
    if(!x) {
        ln=dfs(), rn=dfs();
        na=nb=0; Merge(ret, ln, rn, 1, n);
        ans+=min(na, nb);
    }
    else updata(ret, 1, n, x);
    return ret;
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0), ini();
    cin>>n;
    dfs();
    cout<<ans<<endl;
    return 0;
}

本文链接:https://acxblog.site/archives/sol-luogu-3521.html
本文采用 CC BY-NC-SA 3.0 协议进行许可