Category: Segment-Tree

Length of Longest Increasing Subsequences (LIS) using Segment Tree

#include using namespace std;  #define M 100000  vector tree(4 * M + 1);  void update_tree(int start, int end,                 int update_idx, int length_t,                 int count_c, int idx){            if (start == end        && start == update_idx) {        tree[idx].first            = max(tree[idx].first, length_t);        tree[idx].second = count_c;        return;    }          if (update_idx < start        || end < update_idx) {        return;    }          int mid = (start + end) / 2;      update_tree(start, mid, update_idx,                length_t, count_c,                2 * idx);    update_tree(mid + 1, end, update_idx,                length_t, […]

Continue Reading

Count substrings having frequency of a character exceeding that of another character in a string

#include using namespace std;void update(int ind, vector& segTree,            int n){        ind += n;        segTree[ind]++;    for (; ind > 1; ind >>= 1) {                segTree[ind >> 1] = segTree[ind]                            + segTree[ind ^ 1];    }}int query(int low, int high,          vector& segTree, int n){            low += n;    high += n;    int ans = 0;    while (low < high) {                        if (low % 2) {            ans += segTree[low];            low++;        }        if (high % 2) {            high--;            ans += […]

Continue Reading

Queries to calculate sum of squares of array elements over range of indices [L, R] with updates

   #include using namespace std;    vector seg(400000, 0),     dseg(400000, 0),     a(100000);    vector segSum(400000, 0);    void build(int ind, int low, int high) {          if (low == high) {                     seg[ind] = a[low] * a[low];         segSum[ind] = a[low];         return;     }             int mid = (low + high) / 2;         […]

Continue Reading

Queries to count array elements from a given range having a single set bit

#include using namespace std; bool check(int N) {     if (N == 0)         return 0;     return !(N & (N – 1)); } void build_seg_tree(int ss, int se, int si,                     int tree[], int arr[]) {          if (ss == se) {                  tree[si] = check(arr[ss]);         return;     }          int mid = (ss + se) / 2;      […]

Continue Reading