样例不过,求调
查看原帖
样例不过,求调
1013950
__youzimo2014__楼主2025/1/26 14:42

调了 3 小时 QwQ

#include <iostream>
#include <vector>
using namespace std;
vector<int> a;
long long sort(int right, int left);
long long arraySort(int left, int right, int secondLeft, int secondRight);
int main(int argc, const char * argv[]) {
    // insert code here...
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    a = vector<int>(n);
    for (int i = 0; i < n; i++) { // input
        cin >> a[i];
    }
    cout << sort(0, n - 1) << endl; // 输出答案
    return 0;
}
long long sort(int left, int right) { // 归并排序
    long long ans = 0;
    if (left < right) {
        int mid = (left + right) / 2;
        ans += sort(left, mid);
        ans += sort(mid + 1, right);
        ans += arraySort(left, mid, mid + 1, right);
    }
    return ans;
}
long long arraySort(int left, int right, int secondLeft, int secondRight) { // 双指针合并
    long long ans = 0;
    vector<int> result;
    int i = left, j = secondLeft;
    while (true) {
        if (i > right) {
            while (j <= secondRight) {
                if (a[right] > a[j]) ans++;
                result.push_back(a[j]);
                j++;
            }
            break;
        }
        if (j > secondRight) {
            while (i <= right) {
                result.push_back(a[i]);
                i++;
            }
            break;
        }
        if (a[i] > a[j]) {
            ans++;
            result.push_back(a[i]);
            i++;
        } else {
            result.push_back(a[j]);
            j++;
        }
    }
    for (int i = 0; i < result.size(); i++) {
        a[left + i] = result[i];
    }
    return ans;
}

2025/1/26 14:42
加载中...