File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-09/sol 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/356380170
21
3-
4- /*
5- 1. First, we change the big numbers into simple ranks (1, 2, 3...) so they are easy to count.
6- 2. We treat each number as the middle person and look at its neighbors.
7- 3. We count how many numbers to the left are bigger than our middle number.
8- 4. We count how many numbers to the right are smaller than our middle number.
9- 5. We multiply the bigger-left count by the smaller-right count to get the total triplets.
10- 6. We add up the triplets for every middle number to get the final answer.
11-
12- Time Complexity: O(N \log N)
13- Space Complexity: O(N)
14- */
15-
16-
17- #include < bits/stdc++.h>
18- using namespace std ;
19-
20- int bit[1000005 ];
21- int a[1000005 ];
22- long long left_greater[1000005 ];
23- int n;
24-
25- void update (int idx, int val) {
26- while (idx <= n) {
27- bit[idx] += val;
28- idx += idx & -idx;
29- }
30- }
31-
32- int query (int idx) {
33- int sum = 0 ;
34- while (idx > 0 ) {
35- sum += bit[idx];
36- idx -= idx & -idx;
37- }
38- return sum;
39- }
40-
41- int main () {
42- cin >> n;
43-
44- vector<int > temp;
45- for (int i = 0 ; i < n; i++) {
46- cin >> a[i];
47- temp.push_back (a[i]);
48- }
49-
50- sort (temp.begin (), temp.end ());
51-
52- for (int i = 0 ; i < n; i++) {
53- a[i] = lower_bound (temp.begin (), temp.end (), a[i]) - temp.begin () + 1 ;
54- }
55-
56- for (int i = 0 ; i < n; i++) {
57- left_greater[i] = i - query (a[i]);
58- update (a[i], 1 );
59- }
60-
61- for (int i = 0 ; i <= n; i++) {
62- bit[i] = 0 ;
63- }
64-
65- long long ans = 0 ;
66- for (int i = n - 1 ; i >= 0 ; i--) {
67- long long right_smaller = query (a[i] - 1 );
68- ans += left_greater[i] * right_smaller;
69- update (a[i], 1 );
70- }
71-
72- cout << ans << endl;
73-
74- return 0 ;
75- }
You can’t perform that action at this time.
0 commit comments