Description
Railway tickets were difficult to buy around the Lunar New Year in China, so we must get up early and join a long queue…
The Lunar New Year was approaching, but unluckily the Little Cat still had schedules going here and there. Now, he had to travel by train to Mianyang, Sichuan Province for the winter camp selection of the national team of Olympiad in Informatics.
It was one o’clock a.m. and dark outside. Chill wind from the northwest did not scare off the people in the queue. The cold night gave the Little Cat a shiver. Why not find a problem to think about? That was none the less better than freezing to death!
People kept jumping the queue. Since it was too dark around, such moves would not be discovered even by the people adjacent to the queue-jumpers. “If every person in the queue is assigned an integral value and all the information about those who have jumped the queue and where they stand after queue-jumping is given, can I find out the final order of people in the queue?” Thought the Little Cat.
--by POJ
http://poj.org/problem?id=2828
题目大意:
操作 i val;
序列在i+1位置插入点val;
输出最终的序列结果;
多组数据;
相似的题目 POJ hotel
(学习不深入的结果就是导致对一个点重复学习)
对一个序列预留空位,维护空位个数;
由于后操作影响前操作,故倒序维护操作;
对于每个操作 i val ,把她的val放在当前第i+1个空位上,然后占用该空位;
总结:
线段树可以维护对序列的加点操作,方法如上;
可以维护对序列的合法区间覆盖操作方法见POJ hotel;
这两个操作有相似性——线段树查询合法位置:
对原序列合法的要求,
如,空位个数,显然满足区间叠加性质;
如,区间最大连续空子段,显然也满足;
关键是找出什么是合法二字的要求;
代码如下:
1 #include<cstdio> 2 using namespace std; 3 const int MAXN=200010; 4 int n; 5 int tree[MAXN<<2]; 6 int que[MAXN]; 7 int pos[MAXN],val[MAXN]; 8 void up(int ); 9 void build(int ,int, int ); 10 int find(int ,int ,int ,int ); 11 int main() 12 { 13 int i,j,k; 14 while(scanf("%d",&n)==1){ 15 build(1,n,1); 16 for(i=1;i<=n;i++) 17 scanf("%d%d",&pos[i],&val[i]); 18 for(i=n;i>=1;i--){ 19 pos[i]++; 20 j=find(1,n,1,pos[i]); 21 que[j]=val[i]; 22 } 23 for(i=1;i<=n;i++) 24 printf("%d ",que[i]); 25 printf(" "); 26 } 27 return 0; 28 } 29 void up(int nu){ 30 tree[nu]=tree[nu<<1]+tree[nu<<1|1]; 31 } 32 void build(int l,int r,int nu){ 33 if(l==r){ 34 tree[nu]=1; 35 return ; 36 } 37 int mid=(l+r)>>1; 38 build(l,mid,nu<<1); 39 build(mid+1,r,nu<<1|1); 40 up(nu); 41 } 42 int find(int l,int r,int nu,int x){ 43 int mid=(l+r)>>1,ans; 44 if(l==r){ 45 tree[nu]=0; 46 return l; 47 } 48 if(tree[nu<<1]>=x) 49 ans=find(l,mid,nu<<1,x); 50 else 51 ans=find(mid+1,r,nu<<1|1,x-tree[nu<<1]); 52 up(nu); 53 return ans; 54 }