ZOJ_3279 Ants 線段樹+元素位置

Ants

Time Limit: 2 Seconds      Memory Limit: 32768 KB

echo is a curious and clever girl, and she is addicted to the ants recently.

She knows that the ants are divided into many levels depends on ability, also, she finds the number of each level will change.

Now, she will give two kinds of operations as follow :

First, "p a b", the number of ants in level a change to b.

Second, "q x", it means if the ant's ability is rank xth in all ants, what level will it in?

Input

There are multi-cases, and you should use EOF to check whether it is in the end of the input. The first line is an integern, means the number of level. (1 <=n <= 100000). The second line followsn integers, the ith integer means the number in leveli. The third line is an integerk, means the total number of operations. Then followingk lines, each line will be"p a b" or "q x", and 1 <= x <= total ants, 1 <= a <=n, 0 <= b. What's more, the total number of ants won't exceed 2000000000 in any time.

Output

Output each query in order, one query each line.

Sample Input

3
1 2 3
3
q 2
p 1 2
q 2

Sample Output

2
1
/*利用線段樹查詢第k個元素的位置,線段樹結點保存其兒子的元素個數和
*/
 
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define inf -0x3f3f3f3f
#define mem0(a) memset(a,0,sizeof(a))
const int maxn = 100000+10;
int a[maxn<<2];
void Getsum(int cur){
    a[cur]=a[cur<<1]+a[cur<<1|1];
}
void build(int l,int r,int cur){
    if(l == r){
        scanf("%d",&a[cur]);
        return;
    }
    int mid = (l  + r)>>1;
    build(l,mid,cur<<1);
    build(mid+1,r,cur<<1|1);
    Getsum(cur);
}
void update(int k,int v,int l,int r,int cur){
    if(l == r){
        a[cur]=v;
        return ;
    }
    int mid = ( l + r )>>1;
    if( k <= mid)
        update(k,v,l,mid,cur<<1);
    else
        update(k,v,mid+1,r,cur<<1|1);
    Getsum(cur);
}
int query(int k,int l,int r,int cur){
    if( l == r) return  l;//相當於第l層(level)
    int mid = (l + r )>>1;
    if(k <= a[cur<<1])
        return query(k,l,mid,cur<<1);
    else {
        k-=a[cur<<1];
        return query(k,mid+1,r,cur<<1|1);
    }
}
int main()
{
    int n,aa,b,m;
    while(scanf("%d",&n)!=EOF){
        build(1,n,1);
        scanf("%d",&m);
        while(m--){
            char c[4];
            scanf("%s",c);
            if(c[0]=='p'){
                scanf("%d%d",&aa,&b);
                update(aa,b,1,n,1);
            }
            else {
                scanf("%d",&b);
                printf("%d\n",query(b,1,n,1));
            }
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章