樹——用二叉樹構建線段樹

  上一博文線段樹問題中,用數組表示線段樹,成功AC了,本文用二叉樹表示線段樹,複習一下二叉樹,不過下面這段用二叉樹代碼表示的線段樹是無法AC的,因爲這個代碼的空間複雜度遠高於上一個用結構體數組表示的空間複雜度。

#include<iostream>

#include<cstdlib>

#include<algorithm>

#include<vector>

#include<list>

#include<iterator>

#include<string>

#include<stack>

using namespace std;

#define INF 0x3fffffff


struct NODE {

int left, right, value;

};


struct Tree {

NODE node;

Tree *left, *right;

};


class SegTree {

public:

SegTree() {

}

~SegTree() {

}

void Build(Tree *t,int n,int left,int right);

int Find(Tree *t, int n, int begin, int end);

void Update(Tree *t, int n, int ind, int val);

void Destory(Tree *t);

};


void SegTree::Build(Tree *t, int n, int left,int right){

t->node.left = left;

t->node.right = right;

if (left == right)

{

scanf("%d", &t->node.value);

return;

}

int mid = (left + right) >> 1;

t->left = new Tree();

Build(t->left,n << 1, left, mid);

t->right = new Tree();

Build(t->right,(n << 1) + 1, mid + 1, right);

t->node.value = min(t->left->node.value, t->right->node.value);

}


int SegTree::Find(Tree *t,int n, int begin, int end) {

int p1 = INF, p2 = INF;

if (t->node.left >= begin&&t->node.right <= end)

return t->node.value;

if (begin <= t->left->node.right)

p1 = Find(t->left,n << 1, begin, end);

if (end >= t->right->node.left)

p2 = Find(t->right,(n << 1) + 1, begin, end);

return min(p1, p2);

}


void SegTree::Update(Tree *t,int n, int ind, int val) {

if (t->node.left == t->node.right)

{

t->node.value = val;

}

else

{

if (ind <= t->left->node.right)

Update(t->left,n << 1, ind, val);

if (ind >= t->right->node.left)

Update(t->right,(n << 1) + 1, ind, val);

t->node.value = min(t->left->node.value, t->right->node.value);

}

}


void SegTree::Destory(Tree *t) {

Destory(t->left);

Destory(t->right);

delete t;

t = NULL;

}


int main()

{

int N;

int m;

int s, l, r;

SegTree st;

Tree *t = new Tree();

while (~scanf("%d", &N))

{

st.Build(t,1, 0, N - 1);

scanf("%d", &m);

for (int i = 0; i < m; i++)

{

scanf("%d %d %d", &s, &l, &r);

if (s == 0)

printf("%d\n", st.Find(t,1, l - 1, r - 1));

if (s == 1)

st.Update(t,1, l - 1, r);


}

}

st.Destory(t);

return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章