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 integer n, means the number of level. (1 <= n <= 100000). The second line follows n integers, the ith integer means the number in level i. The third line is an integer k, means the total number of operations. Then following k 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
Author: Lin, Yue
Source: ZOJ Monthly, December 2009
分析:每次更新的时候都递归到端点进行更新
当查询排名的 时候,左边的值大于等于所查排名就向左边搜,否则则向右边搜索,直到搜到叶子节点为止。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=100000;
int sum=0;
int tr[4*N];
void PushUp(int i)
{
tr[i]=tr[2*i]+tr[2*i+1];
}
void build(int i,int l,int r)
{
if(l==r)
{
scanf("%d",&tr[i]);
return;
}
int mid=(l+r)/2;
build(2*i,l,mid);
build(2*i+1,mid+1,r);
PushUp(i);
}
void update(int i,int l,int r,int x,int c)
{
if(l==r&&l==x)
{
tr[i]=c;
return;
}
int mid=(l+r)/2;
if(x<=mid) update(2*i,l,mid,x,c);
else update(2*i+1,mid+1,r,x,c);
PushUp(i);
}
int query(int i,int l,int r,int x)
{
int c;
if(l==r)
{
return l;
}
int mid=(l+r)/2;
if(tr[i<<1]>=x) c=query(2*i,l,mid,x);
else c=query(2*i+1,mid+1,r,x-tr[i<<1]);
return c;
}
int main()
{
int n,k,x,c;
while(~scanf("%d",&n))
{
build(1,1,n);
scanf("%d",&k);
for(int i=1;i<=k;i++)
{
char a[5];
scanf("%s",a);
if(a[0]=='q')
{
scanf("%d",&x);
printf("%d\n",query(1,1,n,x));
}
else
{
scanf("%d%d",&x,&c);
update(1,1,n,x,c);
}
}
}
return 0;
}