CodeforcesSep 19, 2025

Circle of Students

Hazrat Ali

Codeforces

Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after the student 1 in clockwise order (there are no students between them), the student 3 comes right after the student 2 in clockwise order, and so on, and the student n comes right after the student n1 in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student i should be right after the student i1 in counterclockwise order (this condition should be met for every i from 2 to n).

For example, if the indices of students listed in clockwise order are [2,3,4,5,1], then they can start a clockwise round dance. If the students have indices [3,2,1,4] in clockwise order, then they can start a counterclockwise round dance.

Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle.

You have to answer q independent queries.

Input

The first line of the input contains one integer q (1q200) — the number of queries. Then q queries follow.

The first line of the query contains one integer n (1n200) — the number of students.

The second line of the query contains a permutation of indices p1,p2,,pn (1pin), where pi is the index of the i-th student (in clockwise order). It is guaranteed that all pi are distinct integers from 1 to n (i. e. they form a permutation).

Output

For each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO".

Example
Input
5
4
1 2 3 4
3
1 3 2
5
1 2 3 5 4
1
1
5
3 2 1 5 4
Output
YES
YES
NO
YES
YES

Solution
#include <bits/stdc++.h>
using namespace std;

int main() {
 
  int q;
  cin >> q;
  while (q--) {
    int n;
    cin >> n;
    vector<int> p(n);
    int start = 0;
    for (int i = 0; i < n; i++) {
      cin >> p[i];
      if (p[i] == 1) {
        start = i;
      }
    }
    bool cwise = true;
    for (int i = (start + 1 + n) % n; (i + n) % n != start; i++) {
      int cur = (i - 1 + n) % n;
      int nxt = (i + n) % n;
      if (p[cur] + 1 != p[nxt]) {
        cwise = false;
        break;
      }
    }
    bool ccwise = true;
    for (int i = (start - 1 + n) % n; (i + n) % n != start; i--) {
      int prv = (i + n) % n;
      int cur = (i + 1 + n) % n;
      if (p[prv] - 1 != p[cur]) {
        ccwise = false;
        break;
      }
    }
    if (cwise or ccwise) {
      cout << "YES" << endl;
    } else {
      cout << "NO" << endl;
    }
  }
  return 0;
}





Comments