File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-09/sol/ishanrajsingh Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #Submission Link - https://codeforces.com/contest/61/submission/356379545
2+ #Approach - Count triplets i < j < k where a[i] > a[j] > a[k] using two Fenwick Trees implicitly
3+ #Time Complexity - O(n log n)
4+ import sys
5+ sys .setrecursionlimit (10 ** 6 )
6+ input = sys .stdin .read
7+ data = input ().split ()
8+
9+ n = int (data [0 ])
10+ a = list (map (int , data [1 :]))
11+ pos = [0 ] * (n + 1 )
12+
13+ for i in range (n ):
14+ pos [a [i ]] = i + 1
15+
16+ N = n + 10
17+ ft = [0 ] * (N + 1 )
18+
19+ def update (idx , val ):
20+ while idx <= N :
21+ ft [idx ] += val
22+ idx += idx & - idx
23+
24+ def query (idx ):
25+ res = 0
26+ while idx > 0 :
27+ res += ft [idx ]
28+ idx -= idx & - idx
29+ return res
30+
31+ ans = 0
32+ for i in range (n - 1 , - 1 , - 1 ):
33+ r = pos [a [i ]]
34+ smaller_right = query (r - 1 )
35+ ans += smaller_right * query (a [i ] - 1 )
36+ update (r , 1 )
37+
38+ print (ans )
You can’t perform that action at this time.
0 commit comments