Advertisement
Guest User

Untitled

a guest
May 28th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3.  
  4. using namespace std ;
  5.  
  6. ifstream cin ("costperm.in") ;
  7. ofstream cout ("costperm.out") ;
  8.  
  9. class SegmentTree {
  10. public:
  11.     SegmentTree(int n)
  12.     {
  13.         this -> n = n ;
  14.         arb.resize(n * 4) ;
  15.         lazy.resize(n * 4) ;
  16.     }
  17.     void Update (int a, int b, int val) {
  18.         update(1, 1, this->n, a, b, val) ;
  19.     }
  20.     int Query (int poz)
  21.     {
  22.         return query(1, 1, this->n, poz) ;
  23.     }
  24. private:
  25.     int n ;
  26.     vector <int> arb ;
  27.     vector <int> lazy ;
  28.     void lazzie (int nod, int st, int dr) {
  29.         if (lazy [nod] == 0) return ;
  30.         arb [nod] += lazy [nod] ;
  31.         if (st != dr) {
  32.             lazy [nod * 2] += lazy [nod] ;
  33.             lazy [nod * 2 + 1] += lazy [nod] ;
  34.         }
  35.         lazy [nod] = 0 ;
  36.     }
  37.     void update (int nod, int st, int dr, int a, int b, int val)
  38.     {
  39.         if (a <= st and dr <= b) {
  40.             lazy [nod] += val ;
  41.             return ;
  42.         }
  43.         int mij = (st + dr) >> 1 ;
  44.         if (a <= mij)
  45.             update (nod * 2, st, mij, a, b, val) ;
  46.         if (b > mij)
  47.             update (nod * 2 + 1, mij + 1, dr, a, b, val) ;
  48.     }
  49.     int query (int nod, int st, int dr, int pos)
  50.     {
  51.         lazzie (nod, st, dr) ;
  52.         if (st == dr)
  53.             return arb [nod] ;
  54.         int mij = (st + dr) >> 1 ;
  55.         if (pos <= mij) {
  56.             return query(nod * 2, st, mij, pos) ;
  57.         }
  58.         return query(nod * 2 + 1, mij + 1, dr, pos) ;
  59.     }
  60. };
  61.  
  62. int main (){
  63.     int n ;
  64.     cin >> n ;
  65.     vector <int> v (n + 1) ;
  66.     vector <int> poz (n + 1) ;
  67.     SegmentTree *T = new SegmentTree (n) ;
  68.     for (int i = 1 ; i <= n ; ++ i) {
  69.         cin >> v [i] ;
  70.         poz [v[i]] = i ;
  71.         T ->Update(i, i, i) ;
  72.     }
  73.     long long cost = 0 ;
  74.     for (int i = 1 ; i <= n ; ++ i) {
  75.         int cur = T ->Query(poz[i]) ;
  76.         cost = cost + 1LL * (cur - i) * i ;
  77.         T ->Update(1, poz[i], 1) ;
  78.     }
  79.     cout << cost << '\n' ;
  80.     return 0 ;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement