树状数组求逆序数

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define SIZE 50001
struct node
{
	node(): val(0),ord(0){};
	int val;
	int ord;
};
node a[SIZE];
int c[SIZE];
int n=11;
int lowbit(int x)
{
	return x & (-x);
}
void update(int index)
{
	int t=index;
	while(t<=n){
		++c[t];
		t+=lowbit(t);
	}
}
int getsum(int index)
{
	int sum=0;
	int s=index;
	while(s>=1){
		sum+=c[s];
		s-=lowbit(s);
	}
	return sum;
}
bool cmp(node a,node b)
{
	return a.val>b.val;
}
int main()
{
	for(int i=1;i<=n;++i){
		cin>>a[i].val;
		a[i].ord=i;
	}
	sort(a+1,a+n+1,cmp);
	memset(c,0,sizeof(c));
	int ans=0;
	for(int m=1;m<=n;++m){
		update(a[m].ord);
		ans+=getsum(a[m].ord)-1;

	}
	cout<<ans<<endl;
	return 0;
}

你可能感兴趣的:(算法,树状数组)