CodeForces - 459D - Pashmak and Parmida's problem

先上題目:c++

D. Pashmak and Parmida's problem
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 andak = 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).ide

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).this

Output

Print a single integer — the answer to the problem.spa

Sample test(s)
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

   題意:給你n個數,定義一個函數f(l,r,x)表示[l,r]裏面有多少個數是等於x的。如今要求有多少對i,j符合f(1,i,ai)>f(j,n,aj)code

  作法:求出某個ak它的前面和後面各有多少個數等於它自己。而後將這些數用樹狀數組計數,這裏須要先對前面的數離散化(固然,這裏用map來保存也沒有問題),而後像統計逆序對那樣統計就能夠獲得答案了。blog

 

上代碼:ip

 

 1 #include <bits/stdc++.h>
 2 #define lowbit(x) (x&(-x))
 3 #define MAX 1000002
 4 #define ll long long
 5 using namespace std;
 6 
 7 int a[MAX],h[MAX],tot;
 8 ll num[MAX],anum[MAX],f[MAX],r[MAX];
 9 ll c[MAX];
10 int n;
11 
12 void add(int i){
13     for(;i<=MAX-1;i+=lowbit(i)) c[i]++;
14 }
15 
16 ll sum(int i){
17     ll ans=0;
18     for(;i>0;i-=lowbit(i)) ans+=c[i];
19     return ans;
20 }
21 
22 int main()
23 {
24     ll ans,e;
25     //freopen("data.txt","r",stdin);
26     while(scanf("%d",&n)!=EOF){
27         for(int i=0;i<n;i++){
28             scanf("%d",&a[i]);
29             h[i]=a[i];
30             num[i+1]=0;
31         }
32         sort(h,h+n);
33         tot=unique(h,h+n)-h;
34         for(int i=0;i<n;i++){
35             a[i]=lower_bound(h,h+tot,a[i])-h+1;
36         }
37         memset(anum,0,sizeof(anum));
38         for(int i=0;i<n;i++){
39             anum[a[i]]++;
40             f[i]=anum[a[i]];
41         }
42         for(int i=0;i<n;i++){
43             r[i]=anum[a[i]]-f[i]+1;
44         }
45         ans=0;
46         memset(c,0,sizeof(c));
47         for(int i=n-1;i>=0;i--){
48             e=sum(f[i]-1);
49             ans+=e;
50             add(r[i]);
51         }
52         printf("%I64d\n",ans);
53     }
54     return 0;
55 }
/*459D*/
相關文章
相關標籤/搜索