Cinema in Akiba (CIA) is a small but very popular cinema in Akihabara. Every night the cinema is full of people. The layout of CIA is very interesting, as there is only one row so that every audience can enjoy the wonderful movies without any annoyance by other audiences sitting in front of him/her.
The ticket for CIA is strange, too. There are n seats in CIA and they are numbered from 1 to n in order. Apparently, n tickets will be sold everyday. When buying a ticket, if there are k tickets left, your ticket number will be an integer i (1 ≤ i ≤ k), and you should choose the ithempty seat (not occupied by others) and sit down for the film.
On November, 11th, n geeks go to CIA to celebrate their anual festival. The ticket number of the ith geek is ai. Can you help them find out their seat numbers?
Input
The input contains multiple test cases. Process to end of file.
The first line of each case is an integer n (1 ≤ n ≤ 50000), the number of geeks as well as the number of seats in CIA. Then follows a line containing n integers a1, a2, ..., an (1 ≤ ai ≤ n - i + 1), as described above. The third line is an integer m (1 ≤ m ≤ 3000), the number of queries, and the next line is m integers, q1, q2, ..., qm (1 ≤ qi ≤ n), each represents the geek's number and you should help him find his seat.
Output
For each test case, print m integers in a line, seperated by one space. The ith integer is the seat number of the qith geek.
Sample Input
3 1 1 1 3 1 2 3 5 2 3 3 2 1 5 2 3 4 5 1
Sample Output
1 2 3 4 5 3 1 2
题意:第一行一个数 n,表示一共有 n 个空位;第二行有 n 个数,第 i 个数 ai 表示第 i 个人要在坐在第 ai 个空位上(也就是说他前面有ai-1个空位);第三行一个数 m 表示有 m 次访问;第四行 m 次访问,每次访问输入一个整数 bi 表示第 bi 个人坐的位置标号。
分析:线段树,线段树里存放的是这一段里有多少个空位,从下往上更新。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #define MAXN 50005 5 6 using namespace std; 7 8 struct SegTree 9 { 10 int acount,lift,right; 11 }tree[MAXN<<2]; 12 int ans[MAXN]; 13 14 void Build(int r,int L,int R) 15 { 16 tree[r].acount=R-L+1; 17 tree[r].lift=L; 18 tree[r].right=R; 19 int M=(L+R)>>1; 20 if(L<R) 21 { 22 Build(r<<1,L,M); 23 Build(r<<1|1,M+1,R); 24 } 25 } 26 27 int Update(int r,int p) 28 { 29 int L,R,ret; 30 L=tree[r].lift; 31 R=tree[r].right; 32 if(L==R) 33 { 34 tree[r].acount=0; 35 return L; 36 } 37 if(p<=tree[r<<1].acount) 38 ret=Update(r<<1,p); 39 else 40 ret=Update(r<<1|1,p-tree[r<<1].acount); 41 tree[r].acount=tree[r<<1].acount+tree[r<<1|1].acount;//从下往上更新 42 return ret; 43 } 44 45 int main() 46 { 47 int n,m,i,p; 48 while(scanf("%d",&n)==1) 49 { 50 Build(1,1,n); 51 for(i=1;i<=n;i++) 52 { 53 scanf("%d",&p); 54 ans[i]=Update(1,p); 55 } 56 scanf("%d",&m); 57 for(i=1;i<m;i++) 58 { 59 scanf("%d",&p); 60 printf("%d ",ans[p]); 61 } 62 scanf("%d",&p); 63 printf("%d\n",ans[p]); 64 } 65 return 0; 66 }