树状数组求逆序对

板子

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+9;
int li[maxn],a[maxn],n,tot;
ll ans;
class Binary_Index_Tree
{
	private:
		int sumn[maxn];
		int lowbit(int x){
			return x&(-x);
		}
	public:
		void insert(int x){
			for(;x<=tot;x+=lowbit(x))	sumn[x]++;
		}
		int query(int x)
		{
			int ans=0;
			for(;x;x-=lowbit(x))	ans+=sumn[x];
			return ans;
		}
}tree;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		li[i]=a[i];
	}
	sort(li+1,li+1+n);
	tot=unique(li+1,li+1+n)-li-1;
	for(int i=1;i<=n;i++)
	{
		int p=lower_bound(li+1,li+1+tot,a[i])-li;
		ans+=tree.query(tot)-tree.query(p);
		tree.insert(p);
	}
	cout<<ans;
}
posted @ 2020-04-20 15:33  倾叶子佮  阅读(119)  评论(0编辑  收藏  举报