use proconio::input; fn main() { input! { n:usize, a:[usize;n], } let mut seen = vec![false; n + 1]; let mut prev = 0; let mut ok = true; for i in 0..n { if prev != a[i] && seen[a[i]] { ok = false; break; } seen[a[i]] = true; prev = a[i]; } if ok { println!("0"); return; } let mut poss = vec![vec![]; n + 1]; for i in 0..n { poss[a[i]].push(i as i64); } let mut ok = true; for i in 0..=n { if poss[i].len() <= 1 { continue; } let mut uf = UnionFindTree::new(poss[i].len()); f(n, poss[i].len(), &poss[i], &mut uf); if uf.nofcc() != 1 { ok = false; } } let ans = if ok { 1 } else { -1 }; println!("{}", ans); } fn f(m: usize, n: usize, a: &Vec, uf: &mut UnionFindTree) { for i in 0..n { let l = (a[i] - a[(i as i64 - 1).rem_euclid(n as i64) as usize]).rem_euclid(m as i64); if l == 1 { uf.unite(i, (i as i64 - 1).rem_euclid(n as i64) as usize); } let r = (a[(i + 1) % n] - a[i]).rem_euclid(m as i64); if r == 1 { uf.unite(i, (i + 1) % n); } } } use unionfindtree::*; mod unionfindtree { pub struct UnionFindTree { par: Vec, rank: Vec, size: Vec, } impl UnionFindTree { pub fn new(n: usize) -> Self { Self { par: (0..n).collect::>(), rank: vec![0; n], size: vec![1; n], } } #[allow(dead_code)] pub fn same(&mut self, v1: usize, v2: usize) -> bool { self.root(v1) == self.root(v2) } #[allow(dead_code)] pub fn size(&mut self, v: usize) -> usize { let v_root = self.root(v); self.size[v_root] } #[allow(dead_code)] pub fn root(&mut self, v: usize) -> usize { if self.par[v] != v { self.par[v] = self.root(self.par[v]); } self.par[v] } pub fn unite(&mut self, v1: usize, v2: usize) { let mut v1_root = self.root(v1); let mut v2_root = self.root(v2); if v1_root == v2_root { return; } if self.rank[v1_root] < self.rank[v2_root] { std::mem::swap(&mut v1_root, &mut v2_root); } self.par[v2_root] = v1_root; self.size[v1_root] += self.size[v2_root]; if self.rank[v1_root] == self.rank[v2_root] { self.rank[v1_root] += 1; } } #[allow(dead_code)] pub fn nofcc(&mut self) -> usize { let n = self.par.len(); (0..n) .map(|v| self.root(v)) .collect::>() .len() } } }