归并排序开O2优化就全RE,没开就能过

P1908 逆序对

zhijian2000 @ 2019-10-09 13:43:22

很好奇为什么:)

有没有合理的猜测

// #define local
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

vector<int> v;
long res;

long merge(int lo, int mi, int hi)
{
    vector<int> left(v.begin() + lo, v.begin() + mi);
    vector<int> right(v.begin() + mi, v.begin() + hi);

    for (int i = 0, j = 0; i < left.size() || j < right.size(); ) {
        if (i < left.size() && (j == right.size() || left[i] <= right[j]))  {
            v[lo++] = left[i++];
        }
        if (j < right.size() && (i == left.size() || left[i] > right[j])) {
            v[lo++] = right[j++];
            res += left.size() - i;
        }
    }

}
void mergeSort(int lo, int hi)
{
    if (hi - lo < 2) return;

    int mi = (lo + hi) >> 1;
    mergeSort(lo, mi), mergeSort(mi, hi);
    merge(lo, mi, hi);

}

int main()
{
#ifdef local
    freopen("e.txt", "r", stdin);
#endif
    int n; 
    cin >> n;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        v.push_back(x);
    }
    mergeSort(0, n);
    cout << res << endl;
    return 0;    
}

by ud2_ @ 2019-10-09 13:58:14

未定义行为(Undefined behavior)


by ud2_ @ 2019-10-09 13:58:51

可以 #define _GLIBCXX_DEBUG 调试


by 帽子 @ 2019-10-09 14:23:41

merge没有返回值 虽然没有用到返回值 但是优化的时候可能用到了一些相关信息 编译器优化的时候是假设不会发生ub的


by zhijian2000 @ 2019-10-09 16:59:57

谢谢你们~


|