逆序对以及while(cin>>n,n)
作者:
liyuliyu
,
2024-03-20 00:25:14
,
所有人可见
,
阅读 3
#include <iostream>
using namespace std;
const int N=5e5+5;
typedef long long LL;
LL a[N],t[N];
int n;
LL merge(int l,int r)
{
if(l>=r)return 0;
int mid=l+r>>1;
LL res=merge(l,mid)+merge(mid+1,r);
int k=0;
int i=l,j=mid+1;
while(i<=mid&&j<=r)
{
if(a[i]>a[j]){res+=mid-i+1;t[k++]=a[j++];}
else t[k++]=a[i++];
}
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()
{
while(cin>>n,n) //正常读取为true 第2个n用于检测,若成功读取,读取的结果是否为0
{
for(int i=1;i<=n;i++)cin>>a[i]; //这里不要用scanf
cout<<merge(1,n)<<endl;
}
return 0;
}