Bzoj1901 Zju2112 Dynamic Rankings

原题网址:http://www.lydsy.com/JudgeOnline/problem.php?id=1901
我们需要做的是将两个前缀权值线段树相减,我们用外层树状数组,内层权值线段树来实现。外层n棵树分别表示树状数组意义下的权值线段树和,如第i棵树记的是i到i-lowbit(i)+1的权值线段树的和,那么单点修改的时候需要修改log级别个树,查询的时候我们需要提取出l~r区间内的权值线段树,那么就只要将1~r的权值线段树减1~l-1的权值线段树,我们把要加减的log级别的点记下来,这时候我们记下来的点的权值和就是l~r区间内的权值线段树的和,范围是1~MAX_N,我们把这个和与k比较,知道要往左移还是右移,我们把这些点整体左移或右移即可,因为其实这n棵树都是权值线段树,整体移动效果是和不带修改的那道题中单独一棵树上区间左移右移是等效的。

#include<bits/stdc++.h>
const int N = 10050;
const int M = 10050;
const int Node = 8000050;
int n,m,a[N],b[N+M],c[N+M],ref[N+M],tr[Node],lc[Node],rc[Node],rec[50][2],ask[M][3],cnt,s;
int tra(int x){
    int l = 1, r = cnt;
    while (l < r){
        int mid = (l + r + 1) >> 1;
        if (b[mid] <= x)
            l = mid;
        else
            r = mid - 1;
    }
    return c[l];
}
void modify(int rt, int l, int r, int x, int f){
    tr[rt]+=f;
    if (l == r) return;
    if (x <= (l+r)/2){
        if (!lc[rt]) lc[rt] = ++s;
        modify(lc[rt],l,(l+r)/2,x,f);
    }else{
        if (!rc[rt]) rc[rt] = ++s;
        modify(rc[rt],(l+r)/2+1,r,x,f);
    }
}
void modify(int pos, int x, int f){
    for (int i=pos; i<=n; i+=i&-i)
        modify(i,1,c[cnt],x,f);
}
void init(){
    std::sort(b+1,b+cnt+1);
    c[1] = 1; ref[c[1]] = b[1];
    for (int i=2; i<=cnt; i++)
        c[i] = c[i - 1] + (b[i] > b[i - 1]),
        ref[c[i]] = b[i];
    s = n;
    for (int i=1; i<=n; i++)
        modify(i,tra(a[i]),1);
}
int qry(int x, int y, int k){
    int tot = 0;
    for (int i=x; i>0; i-=i&-i) rec[++tot][0] = -1, rec[tot][1] = i;//mistake because more '++'
    for (int i=y; i>0; i-=i&-i) rec[++tot][0] =  1, rec[tot][1] = i;
    int l=1, r=c[cnt];
    while (l < r){
        int sum = 0;
        for (int i=1; i<=tot; i++)
            sum += tr[lc[rec[i][1]]] * rec[i][0];
        if (k <= sum){
            r = (l+r)/2;
            for (int i=1; i<=tot; i++)
                rec[i][1] = lc[rec[i][1]];
        }else{
            l = (l+r)/2+1;
            k -= sum;
            for (int i=1; i<=tot; i++)
                rec[i][1] = rc[rec[i][1]];
        }
    }
    return ref[l];
}
int main(){
    scanf("%d%d",&n,&m);
    for (int i=1; i<=n; i++)
        scanf("%d",&a[i]),
        b[++cnt] = a[i];
    for (int i=1; i<=m; i++){
        char ch[10];
        scanf("%s",ch + 1);
        if (ch[1] == 'C') scanf("%d%d",&ask[i][0],&ask[i][1]), b[++cnt] = ask[i][1];
        if (ch[1] == 'Q') scanf("%d%d%d",&ask[i][0],&ask[i][1],&ask[i][2]);
    }
    init();
    for (int i=1; i<=m; i++)
        if (ask[i][2] == 0){
            modify(ask[i][0],tra(a[ask[i][0]]),-1);
            modify(ask[i][0],tra(a[ask[i][0]] = ask[i][1]),1);//mistake*2 because unrecognize ask[i][0] is subscript
        }else
            printf("%d\n",qry(ask[i][0] - 1,ask[i][1],ask[i][2]));
    return 0;
} 
发布了115 篇原创文章 · 获赞 5 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览