小红的子序列逆序对

https://www.nowcoder.com/practice/189a109747604763932024984f856d99?tpId=376&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

函数:

vector < int > c;

这时候c的size为0,如果直接进行访问 c[i] 会报错。
这里可以使用 c.resize(n),或者c.resize(n, m) 来初始化
前者是使用n个0来初始化,后者是使用n个m来初始化。

#include <iostream>
#include <vector>
using namespace std;

const int mod = 1e9 + 7;
vector<int> c;

int lowbit(int x) {
    return x & -x;
}

void update(int x) {
    while (x < c.size()) {
        ++c[x];
        x += lowbit(x);
    }
}

int query(int x) {
    int ans = 0;
    while (x > 0) {
        ans += c[x];
        x -= lowbit(x);
    }
    return ans;
}

int main() {
    int n, maxa = 0;
    cin >> n;
    vector<int> a(n);
    for (int& ai : a) {
        cin >> ai;
        if (maxa < ai) maxa = ai;
    }
    c.resize(maxa + 1, 0);
    long long ans = 0;
    for (int i = n - 1; i >= 0; --i) {
        ans += query(a[i] - 1);
        update(a[i]);
    }
    for (int i = 2; i < n; ++i) {
        ans = (ans + ans) % mod;
    }
    cout << ans;
}
// 64 位输出请用 printf("%lld")

 

posted @ 2025-07-06 16:44  最近饭吃的很多  阅读(82)  评论(0)    收藏  举报