Buy Tickets POJ - 2828

Buy Tickets

Topic link: POJ-2828

The meaning of the question: n people are queuing up, and each person arrives at a different time, but the latecomer buys a scalper ticket and can jump in the queue, that is to say, if there are three people in the queue, he will be inserted into the second position, and the original second and third positions. Move backward, and finally find the order of alignment after n people are all aligned (each person has a specific number);

We can arrange the latecomer first, the position of the latecomer will not change because of the earlycomer, but the position of the earlycomer will change with the arrival of the latecomer;

Use the line segment tree to insert the a node in reverse order. If the node is unoccupied, insert the node. Otherwise, move backward to the first unmanned area. In fact, after moving backward, it is still the a-th position in the unmanned area;

#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstdio>
using namespace std;
const int maxn = 2e5+100;
int n;
struct node{
    int val, pos;
} a [maxn];
struct Tree{
    int left, right, v;
}tree[maxn<<2];
void build(int m, int l, int r){
    tree[m].left=l;
    tree[m].right=r;
    if(l==r){
        tree[m].v=1;//The node is 1 means no one;
        return;
    }
    int mid=(l+r)>>1;
    build(m<<1, l, mid);
    build(m<<1|1, mid+1, r);
    tree[m].v=tree[m<<1].v+tree[m<<1|1].v;
}
int ans[maxn];
void update(int m, int a, int val){
    //printf("m: %d  left:%d   right:%d    a: %d\n", m, tree[m].left, tree[m].right, a);
    if(tree[m].left==tree[m].right){
        tree[m].v=0;//Insert here, 1 becomes 0;
        ans[tree[m].left]=val;//Record position;
        return;
    }
    if(tree[m<<1].v>=a) update(m<<1, a, val); //v>=a indicates that the first half exceeds a vacancy;
    else update(m<<1|1, a-tree[m<<1].v, val);//The first half is less than a vacancy, go to the second half to find, at this time, the inserted position should be subtracted from the first half vacancy;
    tree[m].v=tree[m<<1].v+tree[m<<1|1].v;
}
/*
void print(int m){
    if(tree[m].left==tree[m].right){
        printf("m:%d  %d ", m, tree[m].v);
        return;
    }
    print(m<<1);
    print(m<<1|1);
}
*/
int main(){
    while(~scanf("%d", &n)){
        int x, y;
        for(int i=0; i<n; i++){
            scanf("%d%d", &a[i].pos, &a[i].val);
        }
        build(1, 1, n);
        //print(1);
        //printf("\n");
        for(int i=n-1; i>=0; i--){
            update(1, a[i].pos+1, a[i].val);
            //print(1);
            //printf("\n");
        }
        for(int i=1; i<=n; i++){
            printf("%d%c", ans[i], i==n?'\n':' ');
        }
    }
    return 0;
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325782804&siteId=291194637