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

本文介绍了一个竞赛编程题目,涉及数组操作及高效求解特定数学问题的方法。通过定义序列上的函数,计算特定条件下的指数对数量。文章提供了一种利用数据结构解决问题的思路,并给出了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值