RMQ(线段树实现)

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值