Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ext/pb_ds/tree_policy.hpp>
- #include <ext/pb_ds/assoc_container.hpp>
- using namespace __gnu_pbds;
- template <class T> using Tree = tree<T, null_type, less<T>,
- rb_tree_tag, tree_order_statistics_node_update>;
- // to get a map, change null_type
- #define ook order_of_key
- #define fbo find_by_order
- int n, pos[MX],p[MX];
- ll numInv;
- Tree<int> T;
- BIT<ll,MX> B;
- ll ari(ll l, ll r) {
- return (r+l)*(r-l+1)/2;
- }
- int main() {
- cin.sync_with_stdio(0); cin.tie(0);
- re(n); FOR(i,1,n+1) re(p[i]);
- FOR(i,1,n+1) pos[p[i]] = i;
- FOR(i,1,n+1) {
- // ps("HUH",i,pos[i]);
- numInv += sz(T)-T.order_of_key(pos[i]);
- T.insert(pos[i]); B.upd(pos[i],pos[i]);
- int ind = sz(T)/2;
- int mid = *T.find_by_order(ind);
- ll ans = 0;
- ll lo = B.sum(mid-1);
- ans += (ll)(mid-ind)*ind-(lo-ari(0,ind-1));
- ll hi = B.sum(n)-B.sum(mid);
- ans += (ll)(hi-ari(ind+1,i-1))-(ll)(mid-ind)*(i-1-ind);
- // ps(ans,mid,lo,hi,numInv+ans);
- ps(numInv+ans);
- }
- // # inversions
- // get middle position
- // you should actually read the stuff at the bottom
- }
- /* stuff you should look for
- * int overflow, array bounds
- * special cases (n=1?), slow multiset operations
- * do smth instead of nothing and stay organized
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement