Advertisement
Guest User

Untitled

a guest
May 26th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. struct card
  6. {
  7.     int w, id;
  8. };
  9.  
  10. struct tree
  11. {
  12.     int w=0, parent=-1;
  13. };
  14.  
  15. void init(tree * T,int l, int r)
  16. {
  17.     int m=(l+r)/2;
  18.     if (r-l > 3)
  19.     {
  20.         init(T,l,m);
  21.         init(T,m+1,r);
  22.     }
  23.     T[(m+r)/2].parent=m;
  24.     T[(l+m)/2].parent=m;
  25.     T[m].w = T[(l+m)/2].w + T[(m+r)/2].w;
  26. }
  27.  
  28. int seek(tree * T,int l, int r, int sl, int sr)
  29. {
  30.     if (l >= sr || r <= sl)
  31.         return 0;
  32.  
  33.     int m=(l+r)/2;
  34.  
  35.     if (l>=sl && r<=sr)
  36.         return T[m].w;
  37.  
  38.     return seek (T,l,m,sl,sr) + seek(T,m+1,r,sl,sr);
  39. }
  40.  
  41. int main ()
  42. {
  43.     std::ios_base::sync_with_stdio(false);
  44.     int n,s=1;
  45.     cin >> n;
  46.     card tab[n];
  47.     for (int i=0;i<n;i++)
  48.     {
  49.         cin >> tab[i].w;
  50.         tab[i].id=i;
  51.     }
  52.  
  53.     while (s<=n)
  54.         s*=2;
  55.     s=2*s-1;
  56.     tree T[s];
  57.     for (int i=0;i<n;i++)
  58.         T[2*i].w=1;
  59.     init(T,0,s);
  60.  
  61.     auto f=[](card a,card b)
  62.     {
  63.         if (a.w != b.w)
  64.             return a.w < b.w;
  65.         else
  66.             return a.id < b.id;
  67.     };
  68.  
  69.     sort(tab,tab+n,f);
  70.  
  71.     int M=n, last=-1,curr,x;
  72.  
  73.     for (int i=0;i<n;i++)
  74.     {
  75.         curr=tab[i].id;
  76.         if (curr > last)
  77.         {
  78.             if (curr!=last+1)
  79.                 M+=seek(T,0,s,2*(last+1),2*curr-1);
  80.         }
  81.         else
  82.         {
  83.             if (curr!=0)
  84.                 M+=seek(T,0,s,0,2*curr-1);
  85.             if (last!=n-1)
  86.                 M+=seek(T,0,s,2*(last+1),2*n-1);
  87.         }
  88.         last=curr;
  89.         x=2*curr;
  90.         while (T[x].parent!=-1)
  91.         {
  92.             T[x].w--;
  93.             x=T[x].parent;
  94.         }
  95.         T[x].w--;
  96.     }
  97.     cout << M;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement