Created
December 6, 2020 10:37
-
-
Save sbsatter/92e32239cd1c0a8641cf07c1aee7885f to your computer and use it in GitHub Desktop.
Solution to Hackerrank's problem: Sherlock and Subqueries with segment tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
const int nmax = 1e5 + 1; | |
const int MIN = -1; | |
int arr[nmax]; | |
pair<int, int> tree [nmax * 4]; | |
void build(int id, int l, int r) { | |
if (l == r) { | |
tree[id] = make_pair(arr[l], 1); | |
return; | |
} | |
int mid = (l + r) / 2; | |
build(2 * id, l, mid); | |
build(2 * id + 1, mid + 1, r); | |
pair<int, int> left = tree[2 * id], right = tree[2 * id + 1]; | |
if (left.first >= right.first) { | |
tree[id] = make_pair(left.first, left.second + (left.first == right.first? right.second : 0)); | |
} else { | |
tree[id] = make_pair(right.first, right.second); | |
} | |
} | |
void update(int id, int l, int r, int idx, int val) { | |
if (l == r) { | |
tree[id] = make_pair(val, 1); | |
return; | |
} | |
int mid = (l + r) / 2; | |
if (idx <= mid) { | |
update(2 * id, l, mid, idx, val); | |
} else { | |
update(2 * id + 1, mid + 1, r, idx, val); | |
} | |
pair<int, int> left = tree[2 * id], right = tree[2 * id + 1]; | |
if (left.first >= right.first) { | |
tree[id] = make_pair(left.first, left.second + (left.first == right.first? right.second : 0)); | |
} else { | |
tree[id] = make_pair(right.first, right.second); | |
} | |
} | |
pair<int,int> query(int id, int left, int right, int a, int b) { | |
if (left > b || right < a) { | |
return make_pair(MIN, 0); | |
} | |
if (left >= a && right <= b) { | |
return tree[id]; | |
} | |
int mid = (left + right) / 2; | |
pair<int,int> l = query(2 * id, left, mid, a, b); | |
pair<int,int> r = query(2 * id + 1, mid + 1, right, a, b); | |
if (l.first > r.first) { | |
return l; | |
} else if (l.first == r.first) { | |
return make_pair(l.first, l.second + r.second); | |
} | |
return r; | |
} | |
int main() { | |
int n, q; | |
cin >> n >> q; | |
for (int i = 1; i <= n; i++) { | |
cin >> arr[i]; | |
} | |
build(1, 1, n); | |
for (int i = 0; i < q; i++) { | |
// query | |
int a, b; | |
cin >> a >> b; | |
cout << query(1, 1, n, a, b).second << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment