Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- using namespace std;
- struct card
- {
- int w, id;
- };
- struct tree
- {
- int w=0, parent=-1;
- };
- void init(tree * T,int l, int r)
- {
- int m=(l+r)/2;
- if (r-l > 3)
- {
- init(T,l,m);
- init(T,m+1,r);
- }
- T[(m+r)/2].parent=m;
- T[(l+m)/2].parent=m;
- T[m].w = T[(l+m)/2].w + T[(m+r)/2].w;
- }
- int seek(tree * T,int l, int r, int sl, int sr)
- {
- if (l >= sr || r <= sl)
- return 0;
- int m=(l+r)/2;
- if (l>=sl && r<=sr)
- return T[m].w;
- return seek (T,l,m,sl,sr) + seek(T,m+1,r,sl,sr);
- }
- int main ()
- {
- std::ios_base::sync_with_stdio(false);
- int n,s=1;
- cin >> n;
- card tab[n];
- for (int i=0;i<n;i++)
- {
- cin >> tab[i].w;
- tab[i].id=i;
- }
- while (s<=n)
- s*=2;
- s=2*s-1;
- tree T[s];
- for (int i=0;i<n;i++)
- T[2*i].w=1;
- init(T,0,s);
- auto f=[](card a,card b)
- {
- if (a.w != b.w)
- return a.w < b.w;
- else
- return a.id < b.id;
- };
- sort(tab,tab+n,f);
- int M=n, last=-1,curr,x;
- for (int i=0;i<n;i++)
- {
- curr=tab[i].id;
- if (curr > last)
- {
- if (curr!=last+1)
- M+=seek(T,0,s,2*(last+1),2*curr-1);
- }
- else
- {
- if (curr!=0)
- M+=seek(T,0,s,0,2*curr-1);
- if (last!=n-1)
- M+=seek(T,0,s,2*(last+1),2*n-1);
- }
- last=curr;
- x=2*curr;
- while (T[x].parent!=-1)
- {
- T[x].w--;
- x=T[x].parent;
- }
- T[x].w--;
- }
- cout << M;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement