码迷,mamicode.com
首页 > 其他好文 > 详细

POJ P2828 Buy Ticket——线段树的其他信息维护

时间:2017-04-10 20:27:50      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:script   clu   --   int   最大   off   iad   const   pos   

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;

这两个操作有相似性——线段树查询合法位置:

对原序列合法的要求,

如,空位个数,显然满足区间叠加性质;

如,区间最大连续空子段,显然也满足;

关键是找出什么是合法二字的要求;

代码如下:

#include<cstdio>
using namespace std;
const int MAXN=200010;
int n;
int tree[MAXN<<2];
int que[MAXN];
int pos[MAXN],val[MAXN];
void up(int );
void build(int ,int, int );
int find(int ,int ,int ,int );
int main()
{
	int i,j,k;
	while(scanf("%d",&n)==1){
		build(1,n,1);
		for(i=1;i<=n;i++)
			scanf("%d%d",&pos[i],&val[i]);
		for(i=n;i>=1;i--){
			pos[i]++;
			j=find(1,n,1,pos[i]);
			que[j]=val[i];
		}
		for(i=1;i<=n;i++)
			printf("%d ",que[i]);
		printf("\n");
	}
	return 0;
}
void up(int nu){
	tree[nu]=tree[nu<<1]+tree[nu<<1|1];
}
void build(int l,int r,int nu){
	if(l==r){
		tree[nu]=1;
		return ;
	}
	int mid=(l+r)>>1;
	build(l,mid,nu<<1);
	build(mid+1,r,nu<<1|1);
	up(nu);
}
int find(int l,int r,int nu,int x){
	int mid=(l+r)>>1,ans;
	if(l==r){
		tree[nu]=0;
		return l;
	}
	if(tree[nu<<1]>=x)
		ans=find(l,mid,nu<<1,x);
	else
		ans=find(mid+1,r,nu<<1|1,x-tree[nu<<1]);
	up(nu);
	return ans;
}

  

POJ P2828 Buy Ticket——线段树的其他信息维护

标签:script   clu   --   int   最大   off   iad   const   pos   

原文地址:http://www.cnblogs.com/nietzsche-oier/p/6690524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!