二分
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int N=100010;
int a[N],b[N],n,ans=0;
void merge(int l,int r)
{
if (l==r) return;
int mid=(l+r)>>1;
merge(l,mid);
merge(mid+1,r);
int t1=l;
int t2=mid+1;
for (int i=l;i<=r;i++)
{
if ((t1<=mid&&a[t1]<=a[t2])||t2>r) {
b[i]=a[t1];
t1++;
}
else
{
b[i]=a[t2];
ans+=(mid-t1+1);
t2++;
}
}
for (int i=l;i<=r;i++) a[i]=b[i];
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
merge(1,n);
printf("%d",ans);
return 0;
}
树状数组
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 500005;
int aa[maxn];
int tree[maxn];
int n;
struct node
{
int v,id;
}a[maxn];
bool cmp(node a,node b)
{
return a.v < b.v;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int t,int x)
{
int i;
for(i=t;i<=n;i+=lowbit(i))
{
cout<<i<<" ";
tree[i] += x;
}
cout<<endl;
}
int getsum(int t)
{
int i,sum =0;
for(i=t;i>=1;i -= lowbit(i))
{
cout<<i<<" ";
sum += tree[i];
}
cout<<endl;
return sum;
}
int main(void)
{
ios::sync_with_stdio(false);
int i;
while(cin>>n&&n)
{
for(i=1;i<=n;i++)
{
cin>>a[i].v;
a[i].id = i;
}
sort(a+1,a+1+n,cmp);
memset(tree,0,sizeof(tree));
for(i=1;i<=n;i++)
aa[a[i].id] = i;
ll ans = 0;
for(i=1;i<=n;i++)
{
update(aa[i],1);
ans += i - getsum(aa[i]);
}
cout<<ans<<endl;
}
return 0;
}