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


分块


#include 
#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(分块)