Round 1040 Div2D Solution in O(n logn) using Policy Based Data Structures

Revision en1, by MasterChief410, 2025-08-06 16:19:03

A few years ago, I read this blog about policy-based data structures in C++ STL and how they can be utilised. Today is the first time I used them :)

The Solution

The problem is quite simple, for each element we are either greedily choosing between the inversions existing due to elements greater than it on its left side or the inversions created by applying the operation to it — these will be the elements greater than it to the right side.

The tutorial calculates these in $$$O(n^2)$$$ time by iterating over the array to calculate the values. However, we can do this in $$$O(n logn)$$$ time by using a balanced BST which can handle both insertions and queries for rank of an element in $$$O(logn)$$$ time. The rank of an element here means the number of elements in the set which are greater than the queried element.

Source: https://stackoverflow.com/questions/18093949/how-to-find-rank-of-an-element-in-stl-set-in-ologn

Code

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
 
#define ll long long
 
typedef tree<int,
             null_type,
             std::greater<int>,
             rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set;
 
void solve(int testCase) {
    ll i, a, n, ans = 0;
    cin >> n;
    ordered_set st;

    for (i = 0; i < n; i++) {
        cin >> a;
        ll b = st.order_of_key(a);
        st.insert(a);
        ans += min(b, n - a - b);
    }
    cout << ans << endl;
}
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t = 1;
    cin >> t;
    for (int testCase = 1; testCase <= t; testCase++)
        solve(testCase);
    return 0;
}

Submission: 332652788

Tags pb_ds, set, tutorial

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English MasterChief410 2025-08-06 16:20:23 17 Tiny change: '--------\nThe prob' -> '--------\n[problem:2129B]\nThe prob'
en1 English MasterChief410 2025-08-06 16:19:03 2006 Initial revision (published)