HDU 6406 - Taotao Picks Apples(线段树查找区间内第一个大于val的位置)

#pragma GCC optimize(2)
#include 
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define line cout<<"-----------------"<> 1;
    }
}tree[maxn<<2];
void init(){
    clr(que);clr(a);clr(suf);clr(ans);clr(tree);
}
void pushup(int x){
    tree[x].maxx = max(tree[x<<1].maxx, tree[x<<1|1].maxx);
}
void build(int x, int l, int r){
    tree[x].l = l; tree[x].r = r;
    if(l == r) {
        tree[x].maxx = a[l];
        return ;
    }
    int mid = tree[x].mid();
    build(x<<1, l, mid);
    build(x<<1|1, mid+1, r);
    pushup(x);
}
int query(int x, int l, int r, int val){
    if(tree[x].l == tree[x].r){
        if(tree[x].maxx > val) return tree[x].l;
        else return -1;
    }
    if(tree[x].l >= l && tree[x].r <= r){
        if(tree[x].maxx <= val) return -1;
    }
    int mid = tree[x].mid();
    if(r <= mid) return query(x<<1, l, r, val);
    else if(l > mid) return query(x<<1|1, l, r, val);
    int temp = query(x<<1, l ,mid, val);
    if(temp != -1) return temp;
    else return query(x<<1|1, mid+1, r, val);
}

int main(){
    int T;
    scanf("%d", &T);
    while(T--){
        init();
        scanf("%d%d", &n, &m);
        for(int i=1; i<=n; i++) scanf("%d", &a[i]);
        build(1, 1, n);
        L = 0, R = -1;
        for(int i=n; i>=1; i--){
            while(L <= R && a[que[R]] <= a[i]) 
                R--;
            que[++R] = i;
            suf[i] = (R - L + 1);
        }
        vector ve;
        int pos, val;
        for(int i=1; i<=m; i++){
            scanf("%d%d", &pos, &val);
            ve.push_back(Q(pos, val, i));
        }
        sort(ve.begin(), ve.end());
        int clock = 0, ma = 0, cc = 0;
        for(int i=1; i<=n; i++){
            while(clock+1 <= m && ve[clock].pos == i){
                int temp = ma;
                int add = 0, cnt = 0;
                if(ve[clock].val > temp) {
                    temp = ve[clock].val;
                    add = 1;
                }
                if(ve[clock].val > temp) 
                    temp = ve[clock].val;
                if(i+1 <= n){
                    pos = query(1, i+1, n, temp);
                    cnt = suf[pos];
                }
                ans[ve[clock].id] = cc + add + cnt;
                clock ++;
            }
            if(ma < a[i]){
                ma = a[i];
                cc++;
            }
        }
        for(int i=1; i<=m; i++)
            printf("%d\n", ans[i]);
    }
    return 0;
}

 

你可能感兴趣的:(HDU,线段树&&树状数组,2018暑假多校补题)