Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <vector>
- using namespace std ;
- ifstream cin ("costperm.in") ;
- ofstream cout ("costperm.out") ;
- class SegmentTree {
- public:
- SegmentTree(int n)
- {
- this -> n = n ;
- arb.resize(n * 4) ;
- lazy.resize(n * 4) ;
- }
- void Update (int a, int b, int val) {
- update(1, 1, this->n, a, b, val) ;
- }
- int Query (int poz)
- {
- return query(1, 1, this->n, poz) ;
- }
- private:
- int n ;
- vector <int> arb ;
- vector <int> lazy ;
- void lazzie (int nod, int st, int dr) {
- if (lazy [nod] == 0) return ;
- arb [nod] += lazy [nod] ;
- if (st != dr) {
- lazy [nod * 2] += lazy [nod] ;
- lazy [nod * 2 + 1] += lazy [nod] ;
- }
- lazy [nod] = 0 ;
- }
- void update (int nod, int st, int dr, int a, int b, int val)
- {
- if (a <= st and dr <= b) {
- lazy [nod] += val ;
- return ;
- }
- int mij = (st + dr) >> 1 ;
- if (a <= mij)
- update (nod * 2, st, mij, a, b, val) ;
- if (b > mij)
- update (nod * 2 + 1, mij + 1, dr, a, b, val) ;
- }
- int query (int nod, int st, int dr, int pos)
- {
- lazzie (nod, st, dr) ;
- if (st == dr)
- return arb [nod] ;
- int mij = (st + dr) >> 1 ;
- if (pos <= mij) {
- return query(nod * 2, st, mij, pos) ;
- }
- return query(nod * 2 + 1, mij + 1, dr, pos) ;
- }
- };
- int main (){
- int n ;
- cin >> n ;
- vector <int> v (n + 1) ;
- vector <int> poz (n + 1) ;
- SegmentTree *T = new SegmentTree (n) ;
- for (int i = 1 ; i <= n ; ++ i) {
- cin >> v [i] ;
- poz [v[i]] = i ;
- T ->Update(i, i, i) ;
- }
- long long cost = 0 ;
- for (int i = 1 ; i <= n ; ++ i) {
- int cur = T ->Query(poz[i]) ;
- cost = cost + 1LL * (cur - i) * i ;
- T ->Update(1, poz[i], 1) ;
- }
- cout << cost << '\n' ;
- return 0 ;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement