Different answers if I use Vector instead of Array while counting Inversions, what could be the cause?

非 Y 不嫁゛ 提交于 2020-01-16 10:08:27

问题


I've been trying to do the count inversions question using mergesort for the past 2-3 days and after much trying, I just picked up the answer from Hackerrank's editorial, now their code is using an Array, and if I use a Vector instead of an Array, the answer is Actual answer + 1 (or different to say the least haven't tried it on many cases). I was wondering what might be the reason for it.

I also have another question on explanation of this code, in particular the variable declarations and their use in the mergei function. I understand the rest of the code conceptually, but because of this part, I have some confusion.

    int ni = ((i+j)/2) + 1, nj = j + 1;
    int s = i;
    int* arr = new int [j - i + 1];
    j = ni; int k = 0;

Code:

void mergei(int a[], int i, int j) {
    int ni = ((i+j)/2) + 1, nj = j + 1;
    int s = i;
    int* arr = new int [j - i + 1];
    j = ni; int k = 0;

    while(i < ni && j < nj) {
        if(a[i] <= a[j]) {
            arr[k++] = a[i++];
        } else {
            arr[k++] = a[j++];
            ans += (ni-i);
        }
    }

    for(; i < ni; i++, k++) arr[k] = a[i];
    for(; j < nj; j++, k++) arr[k] = a[j];
    for(k = 0; s < nj; s++, k++) a[s] = arr[k];
    delete [] arr;
}

void m_sort(int a[], int i, int j) {
    if(i < j) {
        m_sort(a, i, (i+j)/2);
        m_sort(a, ((i+j)/2) + 1, j);
        mergei(a, i, j);
    }
}

int main() {
    // vector<int> a = {2, 1, 3, 1, 2};
    int a[] = {2, 1, 3, 1, 2};
    // int n = a.size();
    int n = sizeof(a)/sizeof(a[0]);
    m_sort(a, 0, n - 1);
    cout << ans << endl;
    return 0;
}

回答1:


I was not passing the Vector by reference, something I didn't have to worry about in case of array.



来源:https://stackoverflow.com/questions/59487483/different-answers-if-i-use-vector-instead-of-array-while-counting-inversions-wh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!