POJ2828 - Buy Tickets

本文介绍了一种使用线段树的数据结构来解决逆序队列问题的方法。通过维护队列中空位的数量,可以高效地完成元素的插入操作。具体实现包括线段树的构建、查询等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

插入队列进行逆向操作,pos代表的也就是放入此人时前面应有pos个空位,用线段树维护空位数量。


/****************************************************/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <stack>
#include <map>
#include <queue>
#include <algorithm>
#include <ctime>
#define EPS 1E-8
#define MAXN 200010
#define INF (~0U >> 2)
#define MOD 1000000007
#define Lson l, mid, rt << 1
#define Rson mid + 1, r, rt << 1 | 1
using namespace std;
typedef long long LL;
/****************************************************/
int num[MAXN << 2], res[MAXN], p;
struct P
{
	int val, pos;
}a[MAXN];
void push_up(int rt)
{
	num[rt] = num[rt << 1] + num[rt << 1 | 1];
}
void build(int l, int r, int rt)
{
	if (l == r)
	{
		num[rt] = 1;
		return;
	}
	int mid = (l + r) >> 1;
	build(Lson);
	build(Rson);
	push_up(rt);
}
void query(int x, int l, int r, int rt)
{
	if (l == r)
	{
		//puts("ok");
		p = l;
		//cout << p << endl;
		num[rt] = 0;
		return;
	}
	int mid = (l + r) >> 1;
	if (num[rt << 1] > x)
		query(x, Lson);
	else
		query(x - num[rt << 1], Rson);
	push_up(rt);
}
int main()
{
	int N;
	while (scanf("%d", &N) != EOF)
	{
		build(1, N, 1);
		for (int i = 0; i < N; i++)
		{
			scanf("%d%d", &a[i].pos, &a[i].val);
		}
		for (int i = N - 1; i >= 0; i--)
		{
			int x = a[i].pos;
			query(x, 1, N, 1);
			res[p] = a[i].val;
		}
		printf("%d", res[1]);
		for (int i = 2; i <= N; i++)
			printf(" %d", res[i]);
		puts("");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值