求逆序对个数(归并排序)
程序员文章站
2022-03-03 07:51:12
...
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e5 + 10;
int a[N],t[N];
inline int read() {
static char c= getchar(); int x=0,f=1;
for(;c>'9'||c<'0';c=getchar()) if(c=='-') f=-1;
for(;c<='9'&&c>='0';c=getchar()) x=(x<<3)+(x<<1)+c-48;
return x*f;
}
ll Merge(int a[],int l,int r)
{
if(l >= r)return 0;
int mid = l + r >> 1;
int i = l,j = mid + 1,k = 0;
ll res = Merge(a,l,mid) + Merge(a,mid+1,r);;
while(i <= mid && j <= r)
{
if(a[i] <= a[j])t[k++] = a[i++];
else
{
res += mid + 1 - i;
t[k++] = a[j++];
}
}
while(i <= mid)t[k++] = a[i++];
while(j <= r)t[k++] = a[j++];
for(int i = l,j = 0;i <= r;i++,j++)a[i] = t[j];
return res;
}
int main()
{
int n;
n = read();
for(int i = 0;i < n;i++)
{
a[i] = read();
}
cout << Merge(a,0,n-1);
return 0;
}
上一篇: 补充知识
下一篇: 前端零碎知识点补充--1