【二维偏序】CF Edu10 D

Problem - D - Codeforces

题意:

【二维偏序】CF Edu10 D_第1张图片

思路:

【二维偏序】CF Edu10 D_第2张图片

Code:

#include 

#define int long long
#define lowbit(x) (x & (-x))

using i64 = long long;

constexpr int N = 2e6 + 10;
constexpr int M = 2e6 + 10;
constexpr int P = 2e6;
constexpr i64 Inf = 1e18;
constexpr int mod = 1e9 + 7;
constexpr double eps = 1e-6;

struct ty {
    int l, r, id;
}a[N];

int n;
int tr[N << 1], ans[N];

void add(int x, int k) {
    for (int i = x; i < N; i += lowbit(i)) tr[i] += k;
}
int sum(int x) {
    int res = 0;
    for (int i = x; i; i -= lowbit(i)) res += tr[i];
    return res;
}
bool cmp(ty x, ty y) {
    if (x.r == y.r) return x.l < y.l;
    return x.r < y.r;
}
void solve() {
    std::cin >> n;

    std::vector V;
    for (int i = 1; i <= n; i ++) {
        int l, r;
        std::cin >> l >> r;
        a[i] = {l, r, i};
        V.push_back(l);
        V.push_back(r);
    }

    std::sort(V.begin(), V.end());
    V.erase(std::unique(V.begin(), V.end()), V.end());

    for (int i = 1; i <= n; i ++) {
        a[i].l = std::lower_bound(V.begin(), V.end(), a[i].l) - V.begin() + 1;
        a[i].r = std::lower_bound(V.begin(), V.end(), a[i].r) - V.begin() + 1;
    }

    std::sort(a + 1, a + 1 + n, cmp);

    for (int i = 1; i <= n; i ++) {
        ans[a[i].id] = i - 1 - sum(a[i].l - 1);
        add(a[i].l, 1);
    }

    for (int i = 1; i <= n; i ++) {
        std::cout << ans[i] << '\n';
    }
}
signed main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int t = 1;

    while (t--) {
        solve();
    }
    
    return 0;
}

 

你可能感兴趣的:(线段树与树状数组,算法)