ZOJ2112单点修改,区间求第K大


分块


#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

#define N 500100

int bl[N], a[N], b[N], L[N], R[N];
int n, m, blk, cnt;

void reset( int x ){
    for ( int i = L[x]; i <= R[x]; i++ ) b[i] = a[i];
    sort( b + L[x], b + R[x] + 1 );
}

void init(){

    blk = sqrt(n);
    if ( n % blk ) cnt = n / blk + 1;
    else cnt = n / blk;
    for ( int i = 1; i <= n; i++ ) bl[i] = (i-1) / blk +1;
    for ( int i = 1; i <= cnt; i++) L[i] = (i-1)*blk+1, R[i] = i * blk;
    R[cnt] = n;
    for ( int i = 1; i <= cnt; i++) reset(i);
}
void update( int x, int w ){
    a[x] = w;
    reset( bl[x] );
}

int query( int l, int r, int k ){
    int lk = bl[l], rk = bl[r];
    int ans = 0;
    if ( lk == rk ){
        for ( int i = l; i <= r; i++) if ( a[i] <= k ) ans ++;
    } else {
        for ( int i = l; i <= R[lk]; i++) if ( a[i] <= k ) ans++;
        for ( int i = L[rk]; i <= r; i++) if ( a[i] <= k ) ans++;
        for ( int i = lk+1; i <= rk-1; i++) ans += upper_bound( b+L[i], b+R[i]+1, k ) - ( b + L[i] );
    }
    return ans;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
        init();
        char ch;
        int x, y, z;
        for(int i = 1; i <= m; i++)
        {
            scanf(" %c", &ch);
            if(ch == 'Q')
            {
                scanf("%d%d%d", &x, &y, &z);
                int l = 1, r = 1e9, res;
                while(l <= r)
                {
                    int mid = (l + r) >> 1;
                    if(query(x, y, mid) >= z) r = mid - 1, res = mid;
                    else l = mid + 1;
                }
                printf("%d\n", res);
            }
            else
            {
                scanf("%d%d", &x, &y);
                update(x, y);
            }
        }
    }
    return 0;
}
发布了190 篇原创文章 · 获赞 19 · 访问量 7万+
展开阅读全文

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

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览