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 indicesk such that: l ≤ k ≤ r andak = x. His task is to calculate the number of pairs of indiciesi, j (1 ≤ i < j ≤ n) such thatf(1, i, ai) > f(j, n, aj).
Help Pashmak with the test.
The first line of the input contains an integer n(1 ≤ n ≤ 106). The second line containsn space-separated integers a1, a2, ..., an(1 ≤ ai ≤ 109).
Print a single integer — the answer to the problem.
7 1 2 1 1 2 2 1
8
3 1 1 1
1
5 1 2 3 4 5
0
题意:给出数组A,定义f(l,r,x)为A[]的下标l到r之间,等于x的元素数。i和j符合f(1,i,a[i])>f(j,n,a[j]),求i和j的种类数。
题解:使用树状数组统计小于某数的元素数量。
STL(map)+树状数组
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <math.h> #include <iostream> #include <map> #include <algorithm> using namespace std; int a[1000005]; int data[1000005]; int mark[1000005]; int lowbit(int x) { return x&(-x); } void add(int p,int num) { if(p<=0)return; while(p<=1000000) { a[p]+=num; p+=lowbit(p); } } int sum(int p) { int ans=0; while(p>0) { ans+=a[p]; p-=lowbit(p); } return ans; } int main() { map<int,int> dicta,dictb; int n; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&data[i]); } for(int i=n-1;i>=0;i--) { dictb[data[i]]++; mark[i]=dictb[data[i]]; add(dictb[data[i]],1); } long long ans=0; for(int i=0;i<n;i++) { dicta[data[i]]++; add(mark[i],-1); ans+=sum(dicta[data[i]]-1); } printf("%I64d\n",ans); return 0; }