POJ 2828 Buy Tickets(多校连萌,线段树模拟插入)

本文介绍如何使用线段树数据结构解决特定队列问题。通过倒序插入的方法,实现对队列的高效操作。

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

题目地址:http://poj.org/problem?id=2828

题意:给一个队列,第一个数是插在哪个位置上,第二个数这个人的标号,问最后的队列是什么样

思路:用线段树倒着插入即可

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn = 200010;
int pos[maxn],value[maxn],sum[maxn<<2],ans[maxn<<2];
void pushup(int rt)
{
    sum[rt] = sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
    sum[rt] = r - l + 1;
    if(l == r) return;
    int m = (l + r)>>1;
    build(lson);
    build(rson);
}
void updata(int pos,int value,int l,int r,int rt)
{
    if(l == r)
    {
        ans[rt] = value;
        sum[rt]--;
        return;
    }
    int m = (l + r)>>1;
    if(pos <= sum[rt<<1]) updata(pos,value,lson);
    else updata(pos-sum[rt<<1],value,rson);
    pushup(rt);
}
void shuchu(int l,int r,int rt)
{
    if(l == r)
    {
        if(l == 1)
            printf("%d",ans[rt]);
        else
            printf(" %d",ans[rt]);
        return;
    }
    int m = (l + r)>>1;
    shuchu(lson);
    shuchu(rson);
}
int main()
{
    int n;
    while(scanf("%d",&n) != EOF)
    {
        for(int i=0; i<n; i++)
            scanf("%d%d",&pos[i],&value[i]);
        build(1,n,1);
        for(int i=n-1; i>=0; i--)
            updata(pos[i]+1,value[i],1,n,1);
        shuchu(1,n,1);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值