Codeforces 459D Pashmak and Parmida's problem(树状数组)*

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.

Examples

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
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<set>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define mod 1e9+7
#define ll long long
#define MAX 1000000000
#define ms memset
using namespace std;
/*
题目大意:给定一个序列,
每个位置上定义一个函数,
即这个位置上数字出现的次数。
要求。。(题目中的公式)

这道题思维比较好,
假定我们已经知道了关于数组的两个序列,
那么如何遍历其中一个后如何体现其大小关系并计数呢。
直接利用前缀和性质,
比如,在位置1上更新1,
那么序列前缀和为1,1,1,。。。
查询2,则得到2。
查询x,可以得到累加次数不超过x的所有计数。

至此,对序列操作的就明显了。代码里见。



*/
const int maxn=1e6+7;
int n,seq[maxn];

int cnt1[maxn],cnt2[maxn];
///利用数据结构map
map<ll,int> ft,bk;

ll tree[maxn];
int lowbit(int x) {return x&(-x);}
void add(int x,int d)
{
    for(;x<=n;tree[x]+=d,x+=lowbit(x));
}
ll sum(int x)
{
    ll res=0;
    for(;x>0;res+=tree[x],x-=lowbit(x));
    return res;
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
         for(int i=1;i<=n;i++)   scanf("%d",&seq[i]);
         ft.clear(),bk.clear();

        for(int i=1;i<=n;i++)   cnt1[i]=++ft[seq[i]];
        for(int i=n;i>=1;i--)   cnt2[i]=++bk[seq[i]];

        memset(tree,0,sizeof(tree));
        for(int i=1;i<=n;i++)
            add(cnt2[i],1);

        ll output=0;
        for(int i=1;i<=n;i++)
        {
            add(cnt2[i],-1);
            output+=sum(cnt1[i]-1);
        }
        printf("%lld\n",output);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/81380283