tzl_Dedicatus545 @ 2020-04-20 12:09:03
#include <iostream>
#include <algorithm>
using namespace std;
long long a[600005],tmp[600005],cnt;
void merge(long long left,long long mid,long long right)
{
long long i=left,j=mid+1,k=left;
while(i<=mid && j<=right)
{
if(a[i]<=a[j])
{
tmp[k++]=a[i++];
}
else
{
cnt++;
tmp[k++]=a[j++];
}
}
while(i<=mid)
{
tmp[k++]=a[i++];
}
while(j<=right)
{
tmp[k++]=a[j++];
}
for(long long i=left;i<=right;i++)
{
a[i]=tmp[i];
}
}
void mergesort(long long left,long long right)
{
if(left>=right)
return ;
long long mid=(left+right)/2;
mergesort(left,mid);
mergesort(mid+1,right);
merge(left,mid,right);
}
int main()
{
ios::sync_with_stdio(false); \\快读
long long n;
cin>>n;
for(long long i=1;i<=n;i++)
cin>>a[i];
mergesort(1,n);
cout<<cnt;
return 0;
}
评测记录
by PragmaGCC @ 2020-04-20 12:10:14
?
您归并排序假的?
by FZzzz @ 2020-04-20 12:11:09
@ljm1069 不能 cnt++
啊,因为它会对很多元素都造成贡献
by PragmaGCC @ 2020-04-20 12:11:14
cnt++
改成
cnt += mid-i+1
by tzl_Dedicatus545 @ 2020-04-20 12:47:10
@反面教材945 请问能说的详细点吗
by tzl_Dedicatus545 @ 2020-04-20 12:48:31
@反面教材945 不太懂
by WanderOvO @ 2020-04-20 13:35:29
数列分为了左半段和右半段,现在,我们发现左半段的a[i]大于右半段的a[j],这说明在左半段中,a[i]以及他后面的元素都比a[j]大,都会和a[j]构成逆序对。所以cnt应该按照楼上说的写