[codility]Array-inversion-count

// you can also use includes, for example:
// #include <algorithm>
long long getInversionCount(vector<int>& workArr, int start, int end)
{
    if(start >= end) return 0;
    int mid = start+(end-start)/2;
    long long inversionCnt = getInversionCount(workArr, start, mid)
                       + getInversionCount(workArr, mid+1, end);
    //...count the inversion count between two part array, when sort them
    vector<int> tmpArr(end-start+1);
    int i = start;
    int j = mid+1;
    int k = 0;
    while(i <= mid || j <= end)
    {
        if(i > mid) tmpArr[k++] = workArr[j++];
        else if(j > end)
        {
            inversionCnt += j-mid-1;
            tmpArr[k++] = workArr[i++];
        }
        else
        {
            if(workArr[i] <= workArr[j])//...= is very important here to make this algorithm right
            {
                inversionCnt += j-mid-1;
                tmpArr[k++] = workArr[i++];
            }
            else tmpArr[k++] = workArr[j++];
        }
    }
    
    for(k = 0; k < tmpArr.size(); ++k)
        workArr[start+k] = tmpArr[k];
    //...return result
    return inversionCnt;
    
}
int solution(const vector<int> &A) {
    // write your code in C++98
    //...using merge sort like methods to calculate the inversion count
    vector<int> workArr = A;
    long long ans = getInversionCount(workArr, 0, workArr.size()-1);
    if(ans > 1000000000) return -1;
    else return (int)ans;
    
}

你可能感兴趣的:([codility]Array-inversion-count)