40pts,求助大佬

P1908 逆序对

Faded_wind123 @ 2024-04-06 15:42:19


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

struct sd {
    ll value;
    ll index;
};

bool compare(sd a, sd b) {
    return a.value < b.value;
}

int main() {
    int n, sum = 0;
    cin >> n;

    sd a[100000];
    for (int i = 0; i < n; i++) {
        cin >> a[i].value;
        a[i].index = i;
    }

    sort(a, a + n, compare);

    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (a[j].index < a[i].index) {
                sum++;
            }
        }
    }

    cout << sum << endl;
    return 0;
}

by Faded_wind123 @ 2024-04-06 15:43:26

开始数组开小了20pts,后面开大了40pts,多数节点re,求助大佬修正


by hair_loss_tree @ 2024-04-06 15:54:17

注意到n>=5*10 5 或许你需要学习归并排序或者是树状数组 推荐前者


by Faded_wind123 @ 2024-04-06 16:01:11

@hair_loss_tree 不是<=吗


by Faded_wind123 @ 2024-04-06 16:03:17

@hair_loss_tree 好的,我去学下


by Laihaocheng @ 2024-04-06 16:07:40

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
long long a[N], tmp[N], sum=0;
void merge_sort(long long q[], long long l, long long r) {
    if (l >= r) return;
    int mid = l + r >> 1;
    merge_sort(q, l, mid), merge_sort(q, mid + 1, r);
    int k = 0, i = l, j = mid + 1;
    while (i <= mid && j <= r)
        if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ];
        else{
            tmp[k ++ ] = q[j ++ ];
            sum+=mid-i+1;
        }
    while (i <= mid) tmp[k ++ ] = q[i ++ ];
    while (j <= r) tmp[k ++ ] = q[j ++ ];
    for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j];
}
int main() {
    int n;
    cin>>n;
    for (int i = 0; i < n; i ++ ) cin>>a[i];
    merge_sort(a, 0, n - 1);
    cout<<sum;
    return 0;
}

by Faded_wind123 @ 2024-04-06 16:29:42

@Laihaocheng 感谢佬,我尽量尝试理解下 ,关注了


|