标签:
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.
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).
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
解析: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