POJ2828

摘要:線段樹,主要考慮用線段樹的查詢。注意反向思維,從最後一個開始判斷位置。

#include <iostream>
#include <cassert>
#include <string.h>
#include <stdio.h>
using namespace std;

const int size = 200000;

typedef struct Node{
    int left;
    int right;
    int posi_nums;
    Node * left_child;
    Node * right_child;
    void Construct(int, int);
    void Insert(int, int);
}Node;

Node sTree[size * 10];
Node *root = &sTree[0];
int in_index[size+1] = {0};
int in_value[size+1] = {0};

int result[size+1] = {0};
int len = 1;

void Node::Construct(int l_arg, int r_arg)
{
    left = l_arg;
    right = r_arg;
    posi_nums = r_arg-l_arg+1;

    if( l_arg == r_arg){
        left_child = right_child = NULL;
        return;
    }

    int mid = (l_arg + r_arg) >> 1;    
    left_child = &sTree[len++];
    right_child = &sTree[len++];
    
    left_child->Construct(l_arg, mid);
    right_child->Construct(mid+1, r_arg);
}

void Node::Insert(int index, int value)
{
    posi_nums--;
    if( left == right){
        result[left] = value;    
        return;
    }    

    assert(left_child && right_child);
    if(left_child->posi_nums >= index){
        left_child->Insert(index, value);
    }else{
        right_child->Insert(index-left_child->posi_nums, value);    
    }    
}

int main()
{
    int n;
    while(scanf("%d", &n) != EOF ){
        root->Construct(1, n);
        memset(result, 0, (n+1)*sizeof(int));
        
        for(int i=1; i<=n; i++){
            scanf("%d%d", &in_index[i], &in_value[i]);
        }
        for(int i=n; i>=1; i--){
            root->Insert(in_index[i]+1, in_value[i]);
        }

        for(int i=1; i<=n; i++){
            printf("%d ", result[i]);
        }    
        printf("/n");
    }
    
    return 0;
}

發佈了63 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章