归并使用int返回类型超时,void不会

P1908 逆序对

epocode @ 2024-06-22 16:20:41

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

long long res = 0;
int merge(int list[], int left, int mid, int right) {
    int j = mid + 1;
    int i = left;
    while (j <= right && i <= mid) {
        if (list[i] > list[j]) {
            res +=  mid - i + 1;
            j++;
        } else {
            i++;
        }
    }
    //执行正常的归并
    i = left;
    j = mid + 1;
    int k  = 0;
    vector<int> tempList(right - left + 1);
    while (i <= mid && j <= right) {
        if (list[i] <= list[j]) {
            tempList[k++] = list[i++];
        } else {
            tempList[k++] = list[j++];
        }
    }
    while (i <= mid) {
        tempList[k++] = list[i++];
    }
    while (j <= right) {
         tempList[k++] = list[j++];
    }
    for (int i = left; i <= right ; i++) {
        list[i] = tempList[i - left];
    }
}

void mergeSort(int list[], int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        mergeSort(list, left, mid);
        mergeSort(list, mid + 1, right);
        merge(list, left, mid, right);
    }
}

int main() {
    int n;
    cin >> n;
    int list[500010];
    for (int i = 0; i < n; i++)  {
        // int input;
        // cin >> input;   
        // list[i] = input;
        cin >> list[i];
    }
    // mergeSort(list, 0, n - 1);通过
    cout << res << endl;
    return 0;
}

我这里mergeSort的返回类型使用int,但是并没有返回任何东西,所有测试用例都会超时。改成void就可以通过,我不明白这是为什么。


by __hqt__ @ 2024-06-22 16:27:31

@epocode 函数(非void类型)不返回是未定义行为,什么都可能发生


by StarsIntoSea_SY @ 2024-06-22 16:28:31

RE 是运行错误不是超时啊喂! @epocode


by ikunTLE @ 2024-06-22 16:33:23

把氧关了


by Kazeno_Akina @ 2024-06-22 16:35:28

@epocode 你UB了。还有RE是运行错误不是超时。


by epocode @ 2024-06-25 19:25:58

@Kazeno_Akina @hqt_ @StarsIntoSea_SY @ikunTLE 明白了,多谢了


|