输入样例:
5 9 1 0 5 4 3 1 2 3 0
输出样例:
6 0
解法一:树状数组+离散化
#include<iostream>
#include<cstring>
#include<algorithm>
#define int long long
using namespace std;
const int N=5e5+5;
int a[N],b[N],tr[N],n,max_;
bool cmp(int x,int y)
{
return a[x]>a[y];
}
int lowbit(int x)
{
return -x&x;
}
void add(int x,int c)
{
for(;x<=n;x+=lowbit(x)) tr[x]+=c;
}
int ask(int x)
{
int res=0;
for(;x;x-=lowbit(x)) res+=tr[x];
return res;
}
signed main()
{
while(cin>>n,n)
{
int res=0;
memset(a,0,sizeof a);
memset(b,0,sizeof b);
memset(tr,0,sizeof tr);
for(int i=1;i<=n;i++) cin>>a[i],b[i]=i;
sort(b+1,b+1+n,cmp);
for(int i=1;i<=n;i++)
{
add(b[i],1);
res+=ask(b[i]-1);
}
cout<<res<<endl;
}
}
解法二:归并排序
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const int N=5e5+5;
LL a[N],temp[N],n,count;
void merg_sort(LL left,LL right)
{
if(left>=right) return ;
LL mid=(left+right)>>1;
merg_sort(left,mid),merg_sort(mid+1,right);
LL k=0,i=left,j=mid+1;
while(i<=mid&&j<=right)
{
if(a[i]<=a[j]) temp[k++]=a[i++];
else
{
temp[k++]=a[j++];
count+=mid-i+1;
}
}
while(i<=mid) temp[k++]=a[i++];
while(j<=right) temp[k++]=a[j++];
for( i=left,j=0;i<=right;i++,j++)
a[i]=temp[j];
}
int main()
{
while(cin>>n,n)
{
memset(a,0,sizeof 0);
memset(temp,0,sizeof temp);
count=0;
for(LL i=0;i<n;i++) cin>>a[i];
merg_sort(0,n-1);
cout<<count<<endl;
}
}