Newcoder 38 E. 珂朵莉的数列(逆序对-BIT)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/V5ZSQ/article/details/83347571

Description

珂朵莉给了你一个序列,有 n ( n + 1 ) 2 \frac{n(n+1)}{2} 个子区间,求出她们各自的逆序对个数,然后加起来输出

Input

第一行一个数$n $表示这个序列 a a 的长度之后一行 n n 个数,第 i i 个数表示 a i a_i

( 1 n 1 0 6 ) (1\le n\le 10^6)

Output

输出一行一个数表示答案

Sample Input

10
1 10 8 5 6 2 3 9 4 7

Sample Output

270

Solution

把所有数字降序排,那么对于当前数字,前面出现的数字都是值不小于该数字值的,其中编号小于该数字编号的即产生了逆序对,对于逆序对 ( l , r ) (l,r) ,对答案贡献为 l ( n r + 1 ) l\cdot (n-r+1) ,假设当前数字编号为 r r ,其前方编号小于该数字编号的编号分别为 l 1 , . . . , l m l_1,...,l_m ,那么以该数字对答案的贡献即为
( n r + 1 ) i = 1 m l i (n-r+1)\cdot \sum\limits_{i=1}^ml_i
故只要把之前每个值在树状数组中其编号位置插入其编号值即可,注意到答案会爆 l o n g   l o n g long\ long ,考虑维护答案除以 1 0 18 10^{18} 的商和余数即可

Code

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int maxn=1000005;
struct BIT 
{
	#define lowbit(x) (x&(-x))
	ll b[maxn];
	int n;
	void init(int _n)
	{
		n=_n;
		for(int i=1;i<=n;i++)b[i]=0;
	}
	void update(int x,int v)
	{
		while(x<=n)
		{
			b[x]+=v;
			x+=lowbit(x);
		}
	}
	ll query(int x)
	{
		ll ans=0;
		while(x)
		{
			ans+=b[x];
			x-=lowbit(x);
		}
		return ans;
	}
}bit;
int n;
P a[maxn];
ll mod=1e18;
int main()
{
	scanf("%d",&n);
	bit.init(n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i].first);
		a[i].second=i;
	}
	sort(a+1,a+n+1);
	ll p=0,q=0;
	for(int i=n;i>=1;i--)
	{
		q+=1ll*(n-a[i].second+1)*bit.query(a[i].second);
		if(q>=mod)p+=q/mod,q%=mod;
		bit.update(a[i].second,a[i].second);
	}
	if(!p)printf("%lld\n",q);
	else printf("%lld%018lld\n",p,q);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/V5ZSQ/article/details/83347571