先给出上一篇文章归并排序模板-CSDN博客里的归并排序模板:
#include<iostream>
using namespace std;const int N = 100010;int n;
int q[N], temp[N];void merge_sort(int q[], int l, int r)
{if(l >= r) return;int mid = (l+r) >> 1;merge_sort(q, l, mid), merge_sort(q, mid+1, r);int i = l, j = mid+1, k = 0;while(i <= mid && j <= r) //对应步骤(3),而且当两个数组的指针都没有越界时才这么做{if(q[i] < q[j]) temp[k++] = q[i++];else temp[k++] = q[j++];}while(i <= mid) temp[k++] = q[i++]; //如果i没有越界,则将i后面的原封不动地拷贝进去while(j <= r) temp[k++] = q[j++]; //如果j没有越界,则将j后面拷贝进去//q和temp数组的范围不同,因此需要两个变量i,j// 注意不是i <= nfor(int i=l, j=0; i <= r; ++i, ++j) q[i] = temp[j]; //步骤(4),注意写法
}int main()
{scanf("%d", &n);for(int i=0;i<n;++i) scanf("%d", &q[i]);merge_sort(q, 0, n-1);for(int i=0;i<n;++i) printf("%d ", q[i]);return 0;
}
下面是求逆序对的过程,可以看到只需要在归并过程中加入计算逆序对数量的步骤即可。
#include<iostream>
using namespace std;const int N = 100010;int n = 0;
int q[N], temp[N];
long long res = 0;void merge_sort(int q[], int l, int r)
{if(l >= r) return;int mid = (l+r) >> 1;merge_sort(q, l, mid), merge_sort(q, mid+1, r);int i = l, j = mid+1, k = 0;while(i <= mid && j <= r){ //归并排序里这里也可以是≤号if(q[i] <= q[j]) temp[k++] = q[i++];//由于逆序对需要严格大于,因此这里是≤号else{temp[k++] = q[j++];res += mid - i + 1;//和归并排序不一样,由于i肯定小于j,因此只有//当q[i]>q[j]时才是逆序对,而且[i,mid]范围内的所有数都能//和q[j]构成逆序对,共mid-i+1个。}}while(i <= mid) temp[k++] = q[i++]; while(j <= r) temp[k++] = q[j++]; for(int i=l, j=0; i <= r; ++i, ++j) q[i] = temp[j]; //这一步不能省去
}int main()
{cin>>n;for(int i=0;i<n;++i) cin>>q[i];merge_sort(q, 0, n-1);cout<<res;return 0;
}