40pts树状数组蒟蒻求条!!!

P1908 逆序对

ChangeYuAN @ 2024-08-05 09:10:55

#include <bits/stdc++.h>
using namespace std;
const int MAXLEN = 5e5 + 5;
int t[MAXLEN], x, y, k, n, m, newa[MAXLEN];

struct Node {
    int id, val;
} a[MAXLEN];

void Change(int x, int k) {
    for (; x <= n; x += x & -(x)) {
        t[x] += k;
    }
    return ;
}

int query(int x) {
    int ret = 0;
    for (; x != 0; x -= x & -(x)) {
        ret += t[x];
    }
    return ret;
}

bool cmp(Node a, Node b) {
    return a.val < b.val;
}

void lisan() {
    sort(a + 1, a + 1 + n, cmp);
    for (int i = 1; i <= n; i++) {
        newa[a[i].id] = i;
    }
}

signed main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &a[i].val);
        a[i].id = i;
    }
    lisan();
    long long ans = 0;
    for (int i = n; i >= 1; i--) {
        ans += query(newa[i] - 1);
        Change(newa[i], 1);
    }
    printf("%d", ans);
    return 0;
}

by ChangeYuAN @ 2024-08-05 09:37:57

此贴结,贴主已自行解决


|