Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define _test int _TEST; cin>>_TEST; while(_TEST--)
- int main()
- {
- _test
- {
- int n;
- cin>>n;
- vector<int> a(n),tmp;
- for(auto &e: a) cin>>e;
- if(is_sorted(a.begin(), a.end()))
- {
- cout<<0<<"\n";
- continue;
- }
- tmp = a;
- reverse(tmp.begin(), tmp.end());
- if(is_sorted(tmp.begin(), tmp.end()))
- {
- cout<<1<<"\n";
- continue;
- }
- int f = 0, y = -1, z = -1,cnt=0;
- auto helper = [&]()
- {
- int mmin = *min_element(a.begin(), a.end());
- int x;
- for(int i=0; i<n; i++)
- {
- if(a[i]==mmin && a[((i-1)+n)%n]>a[i])
- {
- x = i;
- break;
- }
- }
- if(!cnt) y = x;
- else z = x;
- int j = (x+1) % n;
- bool chk = 1;
- while(j!=x && chk)
- {
- chk &= (a[j] >= a[((j-1)+n)%n]);
- j++;
- j %= n;
- }
- cnt++;
- return chk;
- };
- auto cyclicSorted = [&]()
- {
- if(helper()) f ^= 1;
- reverse(a.begin(), a.end());
- if(helper()) f ^= 2;
- return f;
- };
- if(!cyclicSorted())
- {
- cout<<-1<<"\n";
- continue;
- }
- int ans = 1e9;
- if(f&1) ans = min(ans, min(n-y, 2+y));
- if(f&2) ans = min(ans, min(1+n-z, 1+z));
- cout<<ans<<"\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment