题意:输入一组从1到n的数, 判断其是否能构成一个合法的环
p.s.: 合法的环是指由1,2,3,4,,,,n或n,n - 1,n - 2,,,,1首尾相连所构成的环
思路:将输入的数接在原数组的首尾,暴力搜索是否存在长度为n, 且连续上升或连续下降的子串
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 201*5; 4 int a[maxn]; 5 int main() { 6 int q; 7 cin>>q; 8 while(q --){ 9 int n; 10 cin>>n; 11 for(int i = 0; i < n; i ++){ 12 int inp; 13 cin>>inp; 14 a[i] = a[i + n] = a[i + 2*n] = inp; 15 } 16 bool ans = false; 17 for(int i = 0; i < 3*n; i ++){ 18 int cnt = 1; 19 int ptr = i + 1; 20 while(a[ptr] > a[ptr - 1] && ptr < 3*n){ 21 cnt ++; 22 ptr ++; 23 } 24 if(cnt >= n){ 25 ans = true; 26 break; 27 } 28 cnt = 1; 29 ptr = i + 1; 30 while(a[ptr] < a[ptr - 1] && ptr < 3*n){ 31 cnt ++; 32 ptr ++; 33 } 34 if(cnt >= n){ 35 ans = true; 36 break; 37 } 38 } 39 if(ans){ 40 cout<<"YES"<<endl; 41 }else { 42 cout<<"NO"<<endl; 43 } 44 } 45 return 0; 46 }