Codeforces Round #261 (Div. 2) D

Description

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 nspace-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
题意:定义f(l, r, x),是l~r中等于x的有多少个,现在问f(1, i, ai) > f(j, n, aj)中i,j有多少种
解法:预处理f(1, i, ai) ,f(j, n, aj)的个数,然后用树状数组维护
比如最大值为3,则维护到3,如下插入第一个元素
1 0 0 ,我们要求大于2的个数,只需要查询(2-1=1)即(1~1)区间的和就行
即:查询大于x的个数,求(1~x-1)区间的个数
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int ans[2000010];
 4 int ll[2000010],rr[2000010];
 5 int bit(int x)
 6 {
 7     return x&(-x);
 8 }
 9 int add(int adr,int num,int lim)
10 {
11    // cout<<adr<<" "<<num<<" "<<lim<<endl;
12     while(adr<=lim)
13     {
14         ans[adr]+=num;
15         adr+=bit(adr);
16     }
17 }
18 int sum(int lim)
19 {
20     int s=0;
21     while(lim)
22     {
23         s+=ans[lim];
24         lim-=bit(lim);
25     }
26     return s;
27 }
28 int m[2000000];
29 int main()
30 {
31 
32     long long num=0;
33     map<int,int>q,p;
34     int n;
35     int Max=-1;
36     scanf("%d",&n);
37     for(int i=0;i<n;i++)
38     {
39         scanf("%d",&m[i]);
40       //  Max=max(m[i],Max);
41         q[m[i]]++;
42         Max=max(q[m[i]],Max);
43         ll[i]=q[m[i]];
44     }
45     for(int i=n-1;i>=0;i--)
46     {
47         p[m[i]]++;
48         rr[i]=p[m[i]];
49     }
50     //cout<<"A"<<endl;
51     for(int i=n-1;i>0;i--)
52     {
53        // cout<<rr[i]<<endl;
54         add(rr[i],1,Max);
55      //   cout<<i<<endl;
56         num+=sum(ll[i-1]-1);
57     }
58     printf("%lld
",num);
59     return 0;
60 }
 
原文地址:https://www.cnblogs.com/yinghualuowu/p/6582074.html