DEV Community

Guhan M
Guhan M

Posted on

Nested Ranges Count | CSES - Algoritmit ongelmanratkaisussa

Problem: https://cses.fi/alon/task/2169

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <set>
#include <tuple>

using namespace std;

typedef struct SegmentTree {
    int n;
    vector<int> tree;

    SegmentTree(int n) {
        this->n = n;
        tree.assign(2 * (n + 1), 0);
    }

    void increment(int k, long long x) {
        k += n;
        tree[k] += x;
        for (k /= 2; k >= 1; k /= 2) {
            tree[k] = tree[2 * k] + tree[2 * k + 1];
        }
    }

    long long query(int a, int b) {
        a += n;
        b += n;
        long long sum = 0;
        while (a <= b) {
            if (a % 2 == 1) sum += tree[a++];
            if (b % 2 == 0) sum += tree[b--];
            a /= 2;
            b /= 2;
        }
        return sum;
    }

} SegmentTree;

int main() {
    int n;
    cin >> n;

    vector<tuple<long long, long long, int>> arr;
    set<long long> uniquePoints;
    unordered_map<long long, int> pointId;

    for (int i = 0; i < n; i++) {
        long long x, y;
        cin >> x >> y;
        arr.push_back({x, y, i});
        uniquePoints.insert(x);
        uniquePoints.insert(y);
    }

    int tempIdx = 1;
    for (auto it : uniquePoints) {
        pointId[it] = tempIdx;
        tempIdx++;
    }
    sort(arr.begin(), arr.end(), [&](const auto& a, const auto& b) {
        auto [x1, y1, i] = a;
        auto [x2, y2, j] = b;
        if (x1 == x2) return y1 > y2;
        return x1 < x2;
    });


    vector<int> containedBy(n); // How many other ranges contain it
    SegmentTree seg1(tempIdx);
    for (int i = 0; i < n; i++) {
        int r = pointId[get<1>(arr[i])];
        int idx = get<2>(arr[i]);

        containedBy[idx] = i - seg1.query(1, r - 1);
        seg1.increment(r, 1);
    }

    vector<int> contains(n); // How many other ranges it contains
    SegmentTree seg2(tempIdx);
    for (int i = n - 1; i >= 0; i--) {
        int r = pointId[get<1>(arr[i])];
        int idx = get<2>(arr[i]);

        contains[idx] = seg2.query(1, r);
        seg2.increment(r, 1);
    }

    for (int i = 0; i < n; i++) cout << contains[i] << ' ';
    cout << '\n';

    for (int i = 0; i < n; i++) cout << containedBy[i] << ' ';
    cout << '\n';

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)