C++ segment tree solution causing runtime error

14 hours ago 3
ARTICLE AD BOX

I am solving a problem where for each index i, I need to:

Find the smallest index R > i such that A[R] % A[i] == 0

Then compute the maximum in range [i, R]

I optimized the brute force using:

Storing positions of values

Using upper_bound to find the next valid index

Segment tree for range maximum query

However, my solution gives a runtime error.

#include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> bonusST; void build(int index, int low, int high, vector<int>& bonus) { if (low == high) { bonusST[index] = bonus[low]; return; } int mid = (low + high) / 2; build(2 * index + 1, low, mid, bonus); build(2 * index + 2, mid + 1, high, bonus); bonusST[index] = max(bonusST[2 * index + 1], bonusST[2 * index + 2]); } int query(int index, int low, int high, int l, int r) { if (high < l || low > r) return 0; if (l <= low && high <= r) return bonusST[index]; int mid = (low + high) / 2; return max( query(2 * index + 1, low, mid, l, r), query(2 * index + 2, mid + 1, high, l, r) ); } int main() { int N; cin >> N; vector<int> A(N), bonus(N); for (int i = 0; i < N; i++) cin >> A[i]; for (int i = 0; i < N; i++) cin >> bonus[i]; vector<vector<int>> position(N / 2 + 1); for (int i = 0; i < N; i++) position[A[i]].push_back(i); bonusST.resize(4 * N); build(0, 0, N - 1, bonus); int xp = 0; for (int i = 0; i < N; i++) { int R = INT_MAX; for (int j = A[i]; j <= N / 2; j += A[i]) { if (position[j].empty()) continue; auto it = upper_bound(position[j].begin(), position[j].end(), i); if (it != position[j].end()) { R = min(R, *it); } } if (R != INT_MAX) { xp += query(0, 0, N - 1, i, R); } } cout << xp << endl; return 0; }

I suspect the issue is related to recursion in the segment tree or memory limits, but I am not sure.

Can someone point out what is causing the runtime error and how to fix it?

Read Entire Article