Gold14526 @ 2021-10-28 21:23:35
#include<bits/stdc++.h>
using namespace std;
int n,ans;
int a[500001],c[500001];
void merge_sort(int l,int r)
{
if(l>=r)return;
int m=(l+r)/2;
merge_sort(l,m);
merge_sort(m+1,r);
int h=l,h2=m+1;
for(int i=l;i<=r;i++)
{
if(h>m)
{
c[h+h2-m]=a[h2++];
}
else if(h2>r)
{
c[h+h2-m]=a[h++];
}
else if(a[h]>a[h2])
{
ans+=r-h2+1;
c[h+h2-m]=a[h++];
}
else
{
c[h+h2-m]=a[h2++];
}
}
}
int read()
{
int s=0,t=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-')t=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
s=s*10+c-'0';
c=getchar();
}
return s*t;
}
void out(int s)
{
if(s==0)return;
if(s<0)
{
putchar('-');
out(-s);
return;
}
out(s/10);
putchar(s%10+'0');
}
int main()
{
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
n=read();
for(int i=1;i<=n;i++)
{
a[i]=read();
}
merge_sort(1,n);
out(ans);
return 0;
}
by Gold14526 @ 2021-10-28 21:26:35
第二重制版:
#include<bits/stdc++.h>
using namespace std;
int n;
long long ans;
int a[500001],c[500001];
void merge_sort(int l,int r)
{
if(l>=r)return;
int m=(l+r)/2;
merge_sort(l,m);
merge_sort(m+1,r);
int h=l,h2=m+1;
for(int i=l;i<=r;i++)
{
if(h>m)
{
c[h+h2-m]=a[h2++];
}
else if(h2>r)
{
c[h+h2-m]=a[h++];
}
else if(a[h]>a[h2])
{
ans+=r-h2+1;
c[h+h2-m]=a[h++];
}
else
{
c[h+h2-m]=a[h2++];
}
}
}
int read()
{
int s=0,t=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-')t=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
s=s*10+c-'0';
c=getchar();
}
return s*t;
}
void out(long long s)
{
if(s==0)return;
if(s<0)
{
putchar('-');
out(-s);
return;
}
out(s/10);
putchar(s%10+'0');
}
int main()
{
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
n=read();
for(int i=1;i<=n;i++)
{
a[i]=read();
}
merge_sort(1,n);
out(ans);
return 0;
}