Ankit_132

F

Dec 6th, 2023
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1.  
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. #define _test   int _TEST; cin>>_TEST; while(_TEST--)
  7.  
  8. int main()
  9. {
  10.     _test
  11.     {
  12.         int n;
  13.         cin>>n;
  14.  
  15.         vector<int> a(n),tmp;
  16.         for(auto &e: a)     cin>>e;
  17.  
  18.         if(is_sorted(a.begin(), a.end()))
  19.         {
  20.             cout<<0<<"\n";
  21.             continue;
  22.         }
  23.  
  24.         tmp = a;
  25.         reverse(tmp.begin(), tmp.end());
  26.  
  27.         if(is_sorted(tmp.begin(), tmp.end()))
  28.         {
  29.             cout<<1<<"\n";
  30.             continue;
  31.         }
  32.  
  33.         int f = 0, y = -1, z = -1,cnt=0;
  34.  
  35.         auto helper = [&]()
  36.         {
  37.             int mmin = *min_element(a.begin(), a.end());
  38.             int x;
  39.  
  40.             for(int i=0; i<n; i++)
  41.             {
  42.                 if(a[i]==mmin && a[((i-1)+n)%n]>a[i])
  43.                 {
  44.                     x = i;
  45.                     break;
  46.                 }
  47.             }
  48.  
  49.             if(!cnt)        y = x;
  50.             else            z = x;
  51.  
  52.             int j = (x+1) % n;
  53.             bool chk = 1;
  54.  
  55.             while(j!=x && chk)
  56.             {
  57.                 chk &= (a[j] >= a[((j-1)+n)%n]);
  58.                 j++;
  59.                 j %= n;
  60.             }
  61.  
  62.             cnt++;
  63.  
  64.             return chk;
  65.         };
  66.  
  67.         auto cyclicSorted = [&]()
  68.         {
  69.             if(helper())        f ^= 1;
  70.             reverse(a.begin(), a.end());
  71.             if(helper())        f ^= 2;
  72.  
  73.             return f;
  74.         };
  75.  
  76.         if(!cyclicSorted())
  77.         {
  78.             cout<<-1<<"\n";
  79.             continue;
  80.         }
  81.  
  82.         int ans = 1e9;
  83.  
  84.         if(f&1)     ans = min(ans, min(n-y, 2+y));
  85.         if(f&2)     ans = min(ans, min(1+n-z, 1+z));
  86.  
  87.         cout<<ans<<"\n";
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment