int merge(vector<int> &arr, int l, int m, int r)
{
int i = 0;
int p1 = l;
int p2 = m + 1;
int result = 0;
vector<int> help;
help.resize(r - l + 1);
while (p1 <= m && p2 <= r)
{
result += arr[p1] > arr[p2] ? m-p1+1 : 0;
help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= m)
{
help[i++] = arr[p1++];
}
while (p2 <= r)
{
help[i++] = arr[p2++];
}
for (int j = 0; j < help.size(); ++j)
{
arr[l++] = help[j];
}
return result;
}
int mergesort(vector<int> arr, int l, int r)
{
if (arr.size() < 2)
return 0;
if (l == r)
{
return 0;
}
int m = (l + r) / 2;
return mergesort(arr, l, m) + mergesort(arr, m + 1, r) + merge(arr, l, m, r);
}