Skip to content

Instantly share code, notes, and snippets.

@KirillLykov
Created June 21, 2018 21:56
Show Gist options
  • Select an option

  • Save KirillLykov/a9c74fde114cac484bd2be47cad0a84f to your computer and use it in GitHub Desktop.

Select an option

Save KirillLykov/a9c74fde114cac484bd2be47cad0a84f to your computer and use it in GitHub Desktop.
Two lazy tree implemented using array and dynamic memory
#include <bits/stdc++.h>
using namespace std;
typedef long long int lint;
// Explicit tree: using array
const int N = 7;
int tr[4*N + 1];
int maxV[4*N + 1];
void update(int cur, int L, int R, int l, int r) // increments by one corresponding vertices
{
if (l > r) return;
if (L == l && R == r)
++tr[cur];
else {
int M = L + (R - L)/2;
update(2*cur + 1, L, M, l, min(M, r));
update(2*cur + 2, M+1, R, max(M+1, l), r);
}
}
int findMax(int cur, int L, int R, int l, int r) // find max on segment
{
if (l > r) return 0;
if (L == R)
return tr[cur];
int M = L + (R - L)/2;
return tr[cur] + max(
findMax(2*cur+1, L, M, l, min(M, r)),
findMax(2*cur+2, M+1, R, max(M+1,l), r));
}
// Implicit: using pointers
struct Node {
lint data;
shared_ptr<Node> left, right;
Node() : data(0) {}
};
typedef shared_ptr<Node> NodePtr;
NodePtr root(new Node);
void updateD(NodePtr cur, int L, int R, int l, int r) {
if (l > r) return;
if (L == l && R == r) {
cur->data += 1;
} else {
int M = L + (R - L)/2;
if (cur->left == nullptr)
cur->left.reset(new Node);
updateD(cur->left, L, M, l, min(M, r));
if (cur->right == nullptr)
cur->right.reset(new Node);
updateD(cur->right, M+1, R, max(M+1,l), r);
}
}
int findMaxD(NodePtr cur, int L, int R, int l, int r)
{
if (l > r) return 0;
if (cur == nullptr) return 0;
int M = L + (R - L)/2;
return cur->data + max(
findMaxD(cur->left, L, M, l, min(M, r)),
findMaxD(cur->right, M+1, R, max(M+1,l), r));
}
int main(int, char**) {
std::ios::sync_with_stdio(false);
update(0, 0, N, 0, 5);
update(0, 0, N, 0, 2);
//for (int i = 0; i < N; ++i)
// cout << tr[i] << " ";
cout << findMax(0, 0, N, 3, 4) << endl;
updateD(root, 0, N, 0, 5);
updateD(root, 0, N, 0, 2);
cout << findMaxD(root, 0, N, 3, 4) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment