Error in the problem of finding the maximum in the segment tree

0

When compiling the program throws this error:

Unhandled exception at 0x000418B9 в laba6c++.exe: 0xC00000FD: Stack overflow (characteristic: 0x00000001, 0x00402FFC).

I think the error is due to too many recursions of the maxim function, but I don't know how to fix it

#include <iostream>
#include <cstdio>
#include <vector>

const int INF = 1000;

using namespace std;

int const n = 5;
int t[4 * n];
int a[] = { 2, 2, 2, 1, 5 };

int find_max(int a, int b) {
    if (a > b) return a;
    if (b > a) return b;
    return a;
}

int find_min(int a, int b) {
    if (a < b) return a;
    if (b < a) return b;
    return a;
}


void build(int a[], int v, int tl, int tr) {    //а-массив с числами, v-текущая вершина, tl & tr - границы соответствующие текущей вершине
    if (tl == tr)
        t[v] = a[tl];       //определяем номер для листа дерева
    else {
        int tm = (tl + tr) / 2;         // tm-середина
        build(a, v * 2, tl, tm);        //строим левую часть дерева
        build(a, v * 2 + 1, tm + 1, tr);        //строим правую часть дерева
        t[v] = find_max(t[v * 2], t[v * 2 + 1]);            //определяем номер текущей вершины
    }
}

int maxim(int v, int tl, int tr, int l, int r) {
    if (l > r)
        return -INF;
    if (l == tl && r == tr)
        return t[v];
    int tm = (tl + tr) / 2;
    return find_max(maxim(v * 2, tl, tm, l, find_min(r, tm)), maxim(v * 2 + 1, tm + 1, tr, find_max(l, tm + 1), r));
}

int main() {
    build(a, 1, 0, n - 1);
    cout << maxim(1, 0, n - 1, 2, 5);
}
c++
recursion
stack-overflow
segment-tree
asked on Stack Overflow Dec 20, 2019 by Nikita noob • edited Dec 21, 2019 by Pmpr

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0