代码中在main函数写了测试用例,可以修改哈。
#include "pch.h"
#include <iostream>
#include <vector>
using namespace std;
int merge(vector<int>& arr, int L, int M, int R) {
int ans = 0;
vector<int>help(R - L + 1);
int i = 0;
int p1 = L;
int p2 = M + 1;
//每个数右边有几个比自己小的
while (p1 <= M && p2 <= R) {
if (arr[p1] <= arr[p2])//产生一段
{
ans = ans + ((p2 - 1) - (M + 1)) + 1;
help[i++] = arr[p1++];
}
else {
help[i++]= arr[p2++];
}
}
while (p1 <= M) {
ans = ans + ((p2 - 1) - (M + 1)) + 1;
help[i++] = arr[p1++];
}
while (p2 <= R) {
help[i++] = arr[p2++];
}
for (i = 0; i < R - L + 1; i++) {
arr[L + i] = help[i];
}
return ans;
}
int process(vector<int>& arr, int L, int R) {
if (L == R) {
return 0;
}
int mid = L + ((R - L) >> 1);
return process(arr, L, mid)+
process(arr, mid + 1, R)+
merge(arr, L, mid, R);
}
int main()
{
vector<int> arr{ 1,3,2,3,1 };
cout<<"--------结果有几个:"<<process(arr, 0, arr.size()-1);
for (int i = 0; i < arr.size(); i++)
{
cout <<endl<<"i="<<i<<","<< arr[i] << endl;
}
}