ZOJ 3279 Ants

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3279

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 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<stdio.h>
#include<cstring>
using namespace std;

int t[100001];
int n;
void add(int x,int y)
{
    for(;x<=n;x+=x&-x)
    t[x]+=y;
}
int sum(int x)
{
    int ans=0;
    for(;x>0;x-=x&-x)
    {
        ans+=t[x];
    }
    return ans;
}

int main()
{
    int a,tt,x,y,i,j,r,l,m;
    char c;
    while(scanf("%d",&n)!=EOF)
    {
        memset(t,0,sizeof(t));
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a);
            add(i,a);
        }
        scanf("%d",&tt);
        for(i=1;i<=tt;i++)
        {
            getchar();
            scanf("%c",&c);
            if(c=='q')
             {
                 scanf("%d",&x);
                 l=1;
                 r=n;
                 m=(l+r)/2;
                 while(l<=r)
                 {
                     if(x>sum(m-1)&&x<=sum(m))
                      {
                          printf("%d\n",m);
                          break;
                      }
                      else if(x<=sum(m-1))
                      {
                          r=m-1;
                          m=(l+r)/2;

                      }
                      else  if(x>sum(m))
                      {
                          l=m+1;
                          m=(l+r)/2;
                      }
                 }

             }
             else
             {
                 scanf("%d %d",&x,&y);
                 add(x,y-sum(x)+sum(x-1));
             }
        }
    }
    return 0;
}

  


posted @ 2011-07-27 17:49  Crazy_yiner  阅读(295)  评论(0编辑  收藏  举报