D Pashmak and Parmida‘s problem

https://codeforces.com/problemset/problem/459/D

Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.

There is a sequence a that consists of n integers a 1, a 2, ..., a n. Let's denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and a k = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, a i) > f(j, n, a j).

Help Pashmak with the test.

Input

The first line of the input contains an integer n (1 ≤ n ≤ 106). The second line contains n space-separated integers a 1, a 2, ..., a n (1 ≤ a i ≤ 109).

Output

Print a single integer — the answer to the problem.

Examples

input

Copy

7
1 2 1 1 2 2 1

output

Copy

8

input

Copy

3
1 1 1

output

Copy

1

input

Copy

5
1 2 3 4 5

output

Copy

0

 

思路:树状数组求逆序对。

先用map预处理出所求,然后把两个所求当作求逆序对的过程。我觉得求逆序对模拟的过程好理解一些。如果不太会的话可以去luogu做一下逆序对的板子题。

模拟的过程来自博客:https://www.cnblogs.com/yuiffy/p/3916512.html

n=7

A  1  2  1  1  2  2  1

R  4  3  3  2  2  1  1

L  1  1  2  3  2  3  4

其中A为给定的数组,Rj为f(j,n,a[j]),Li为f(1,i,a[i])。

对每个Li,我们要统计的其实就是符合(j>i,且Rj

这样我们可以用树状数组,把Rj各个数的数量全存到树状数组里,例如这个样例就是4有1个,3有2个,2有2个,1有2个。然后从左到右遍历Li,每次从树状数组里删掉Rj,并且求sum(Li-1),也就是树状数组中1~Li-1的和,也就是比Li小的元素个数。

例如这个样例,到L3时,树状数组里记了2个1和2个2(1个4和2个3在之前被删掉了),L3=2,则sum(L3-1)=sum(2)=1的数量+2的数量=3。ans+=3。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define debug(a) cout<<#a<<"="<map1,map2;
LL add(LL x,LL d){
	while(x<=n){
		tree[x]+=d;
		x+=lowbit(x);
	}
}
LL sum(LL x){
	LL ans=0;
	while(x>0){
		ans+=tree[x];
		x-=lowbit(x);
	}
	return ans;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  cin>>n;
  for(LL i=1;i<=n;i++){
  	 cin>>a[i];
  }
  for(LL i=1;i<=n;i++){
  	f1[i]=++map1[a[i]];
  }
  for(LL i=n;i>=1;i--){
  	f2[i]=++map2[a[i]];
  }
  for(LL i=1;i<=n;i++){
  	add(f2[i],1);
  }
  LL res=0;
  for(LL i=1;i<=n;i++){
  	add(f2[i],-1);
  	res+=sum(f1[i]-1);
  }
  cout<

 

你可能感兴趣的:(树状数组,数据结构)