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
这道题让我想起了今天网络赛的一题。。。模型几乎是一样的,只是当时怎么接触过前缀和。。。加上二分搜索答案。
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <string> #include <algorithm> #include <queue> using namespace std; const int maxn = 100000+10; int A[maxn],C[maxn]; int n; int lowbit(int x){ return x&-x; } void add(int x,int d){ while(x <= n){ C[x] += d; x += lowbit(x); } } int sum(int x){ int ret = 0; while(x > 0){ ret += C[x]; x -= lowbit(x); } return ret; } int binary_search(int x){ int l = 1, r = n; int ans=1; while(l <= r){ int mid = (l+r)/2; int t = sum(mid); if(t >= x){ r = mid-1; ans = mid; }else{ l = mid+1; } } return ans; } void solve(){ int m; scanf("%d",&m); while(m--){ char op; cin >> op; if(op=='q'){ int k; scanf("%d",&k); cout<<binary_search(k)<<endl; }else{ int a,b; scanf("%d%d",&a,&b); add(a,b-A[a]); A[a] = b; } } } void input(){ memset(C,0,sizeof(C)); for(int i = 1; i <= n; i++){ scanf("%d",&A[i]); add(i,A[i]); } } int main(){ while(~scanf("%d",&n)){ input(); solve(); } return 0; }