码迷,mamicode.com
首页 > 编程语言 > 详细

Codeforces Round #261 (Div. 2) D. Pashmak and Parmida's problem (树状数组)

时间:2015-06-18 19:56:26      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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

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



解析:f(l,?r,?x) 表示 l?≤?k?≤?r and ak?=?x的个数,要计算  f(1,?i,?ai)?>?f(j,?n,?aj)且i,?j (1?≤?i?<?j?≤?n) 的对数.

先预处理f(1, i, ai)和f(j, n, aj),然后就特别像逆序数了。用树状数组搞一下就行了。




AC代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;

int a[N], f[N], g[N], c[N];

map<int, int> m;

int lowbit(int x){
    return x & -x;
}

void add(int x, int d){
    for( ; x < N; x += lowbit(x)) c[x] += d;
}

int sum(int x){
    int ret = 0;
    for( ; x > 0; x -= lowbit(x)) ret += c[x];
    return ret;
}

int main(){
    #ifdef sxk
        freopen("in.txt", "r", stdin);
    #endif // sxk

    int n;
    while(~scanf("%d", &n)){
        m.clear();
        for(int i=1; i<=n; i++){
            scanf("%d", &a[i]);
            m[ a[i] ] ++;
            f[i] = m[ a[i] ];        //f(1, i, ai)
        }
        m.clear();
        for(int i=n; i>0; i--){
            m[ a[i] ] ++;
            g[i] = m[ a[i] ];        //f(j, n, aj)
        }
        memset(c, 0, sizeof(c));
        long long ans = 0;
        for(int i=n-1; i>0; i--){
            add(g[i+1], 1);
            ans += sum(f[i] - 1);
        }
        printf("%lld\n", ans);

    }
    return 0;
}


Codeforces Round #261 (Div. 2) D. Pashmak and Parmida's problem (树状数组)

标签:

原文地址:http://blog.csdn.net/u013446688/article/details/46549677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!