T_T第一个线段树程序,还没A过题,不过也很感动, 先贴出来
//下标从0开始,输入-1 -1 结束.求每一段区间之间的最大值。
#include <cstdio>
#include <cstdlib>
typedef struct Treenode{
int ld, rd;
struct Treenode *lc, *rc;
int key;
}node;
int mymax(int a, int b){
return a > b ? a : b;
}
node* buildtree(int a, int b){
node *p = (node *)malloc(sizeof(node));
p -> ld = a;
p -> rd = b;
p -> key = -1;
if (a == b){
return p;
}
p -> lc = buildtree(a, (a + b) / 2);
p -> rc = buildtree((a + b) / 2 + 1, b);
return p;
}
void insert(node *T, int pos, int key){
if (T -> ld == T -> rd){
T -> key = key;
return ;
}
if (pos <= (T -> ld + T -> rd) / 2){
insert(T -> lc, pos, key);
}
else{
insert(T -> rc, pos, key);
}
T -> key = mymax(T -> lc -> key, T -> rc -> key);
}
int search(node *T, int a, int b){
int res = -999999999;
if (a <= T -> ld && T -> rd <= b){
return T -> key;
}
if (a <= (T -> ld + T -> rd) / 2){
res = mymax(search(T -> lc, a, b), res);
}
if (b > (T -> ld + T -> rd) / 2){
res = mymax(search(T -> rc, a, b), res);
}
return res;
}
int main(void){
int arr[11] = {1, 3, 646, 34, 20, 30 , 60 , 36, 892, 1, -1};
int left, right;
int i, j;
node *linetree = buildtree(0, 10);
for (i = 0; i < 11; i++){
insert(linetree, i, arr[i]);
}
while (scanf("%d%d", &left, &right), left != -1 || right != -1){
printf("%d -- %d: %d\n", left, right, search(linetree, left, right));
}
return 0;
}