Advertisement
ec1117

Untitled

Sep 29th, 2020 (edited)
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <ext/pb_ds/tree_policy.hpp>
  2. #include <ext/pb_ds/assoc_container.hpp>
  3. using namespace __gnu_pbds;
  4.  
  5. template <class T> using Tree = tree<T, null_type, less<T>,
  6.     rb_tree_tag, tree_order_statistics_node_update>;
  7. // to get a map, change null_type
  8.  
  9. #define ook order_of_key
  10. #define fbo find_by_order
  11.  
  12. int n, pos[MX],p[MX];
  13. ll numInv;
  14. Tree<int> T;
  15. BIT<ll,MX> B;
  16.  
  17. ll ari(ll l, ll r) {
  18.     return (r+l)*(r-l+1)/2;
  19. }
  20.  
  21. int main() {
  22.     cin.sync_with_stdio(0); cin.tie(0);
  23.     re(n); FOR(i,1,n+1) re(p[i]);
  24.     FOR(i,1,n+1) pos[p[i]] = i;
  25.     FOR(i,1,n+1) {
  26.         // ps("HUH",i,pos[i]);
  27.         numInv += sz(T)-T.order_of_key(pos[i]);
  28.         T.insert(pos[i]); B.upd(pos[i],pos[i]);
  29.         int ind = sz(T)/2;
  30.         int mid = *T.find_by_order(ind);
  31.         ll ans = 0;
  32.         ll lo = B.sum(mid-1);
  33.         ans += (ll)(mid-ind)*ind-(lo-ari(0,ind-1));
  34.         ll hi = B.sum(n)-B.sum(mid);
  35.         ans += (ll)(hi-ari(ind+1,i-1))-(ll)(mid-ind)*(i-1-ind);
  36.         // ps(ans,mid,lo,hi,numInv+ans);
  37.         ps(numInv+ans);
  38.     }
  39.     // # inversions
  40.     // get middle position
  41.     // you should actually read the stuff at the bottom
  42. }
  43.  
  44. /* stuff you should look for
  45.     * int overflow, array bounds
  46.     * special cases (n=1?), slow multiset operations
  47.     * do smth instead of nothing and stay organized
  48. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement