您的位置:首页 > 其它

J - Pashmak and Parmida's problem CodeForces - 459D(思维优化+树状数组)

2017-07-27 22:09 567 查看
J - Pashmak and Parmida’s problem CodeForces - 459D

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 a1, a2, …, an. Let’s denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, ai) > f(j, n, aj).

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 a1, a2, …, an (1 ≤ ai ≤ 109).

Output

Print a single integer — the answer to the problem.

Example

Input

7

1 2 1 1 2 2 1

Output

8

Input

3

1 1 1

Output

1

Input

5

1 2 3 4 5

Output

0

题目大意:定义一个函数f(n,m,a【m】)返回值为下标从n-m的数组a中与a【m】值相同的数的个数题目中是要找出 f(1, i, ai) > f(j, n, aj)的i,j的对数

解题思路:n<=1e6很明显直接暴力会超时,这时想到用树状数组来存后缀既f(j,n,aj)这样算出前缀和后缀后前缀f(1,i,ai)与后缀比较为o(1)然后当前i,j对数的计算为o(logn)然后这样还是会超时=-=

需要对找f(1,i,ai)的过程进行优化想到可以借用前面的结果来优化

直接开下标为a【i】的数组会造成空间的巨大浪费所以想到借助c++stl中的map来存储。

ac代码

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N=1e6+5;
int arr
,fi
,fj
;
int n;
void add(int x)
{
while(x<=n)
{
arr[x]++;
x+=x&(-x);
}
}
int sum(int x)
{
int s=0;
while(x>0)
{
s+=arr[x];
x-=x&(-x);
}
return s;
}
int main()
{
int i;
map<int,int>mp;
scanf("%d",&n);
for(i=1;i<=n;i++)scanf("%d",&arr[i]);
for(i=1;i<=n;i++)
{
fi[i]=++mp[arr[i]];
}
mp.clear();
for(i=n;i>=1;i--)
{
fj[i]=++mp[arr[i]];
}
memset(arr,0,sizeof(arr));
LL ans=0;
for(i=n-1;i>=2;i--)
{
add(fj[i+1]);
ans+=sum(fi[i]-1);
}
cout<<ans<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  树状数组
相关文章推荐