【POJ】Buy Tickets(思路 + 线段树)

一开始没有思路,之后问了一下学长,需要逆向处理输入。

最后一个加入队列的肯定是没有冲突的,所以我们可以从最后一个开始处理,从后往前,找第 i + 1个空着的地方。

线段树的话记录 区间中 空白位置的个数。

134418332013010521002828Accepted5368K1704MSC++1690B2014-09-14 21:19:45

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long LL;
/*=====================================*/
const int maxn = 200000 + 10;
int tree[maxn << 2];
int  ans[maxn << 2];
int array[maxn],value[maxn];
int n;
void BuildTree(int L,int R,int pos){
    if(L == R){
        tree[pos] = 1; //在区间L,R之间有几个空位
        return ;
    }
    int m = (L + R) >> 1;
    BuildTree(L,m,pos << 1);
    BuildTree(m + 1, R ,(pos << 1)|1);
    tree[pos] = tree[pos << 1] + tree[(pos << 1)|1];
    return ;
}
void UpDate(int k,int L,int R,int pos,int value){
    if(L == R){
        ans[pos] = value;
        tree[pos] --;
        return ;
    }
    int m = (L + R) >> 1;
    int e1 = tree[pos << 1];
    int e2 = tree[(pos << 1)|1];
    if(e1 >= k)
        UpDate(k,L,m,pos << 1,value);
    else
        UpDate(k - e1,m + 1,R, (pos << 1)|1,value);
    tree[pos] = tree[pos << 1] + tree[(pos << 1)|1];
}
void ShowTree(int L,int R,int pos){
    if(L == R){
        printf("%d",ans[pos]);
        return ;
    }
    int m = (L + R)  >> 1;
    ShowTree(L, m, pos << 1);printf(" ");ShowTree(m + 1, R ,(pos << 1)|1);
}
int main(){
    while(scanf("%d",&n) != EOF){
        BuildTree(1,n,1); //log(n)的时间复杂度建树
        for(int i = 0 ; i < n ; i++)
            scanf("%d%d",&array[i],&value[i]);
        for(int i = n - 1 ; i >= 0 ; i --){ //找到第 i + 1个为空的位置
            UpDate(array[i] + 1,1,n,1,value[i]);  //nlog(n)的时间复杂度进行更新
        }
        ShowTree(1,n,1);  //log(n)的时间复杂度打印路径
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值