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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值