Preprocess the nearest adjacent element to the left and right of each element.
For an interval [L, r] and an element within an interval, this element is unique within this interval and only if the nearest adjacent element of the left and right side is not in this interval. This allows O (1) to complete the query.
First, find out if the entire string has a unique element, and if not, the entire sequence is boring.
If there is, assuming this unique element subscript is p, then if the subsequence [0, P-1] and [P+1, n-1] is not boring, then this sequence is not boring.
If you look for a unique element from one end, the worst case is O (n). So you can find it from both ends, the total time complexity is O (NLOGN).
1#include <bits/stdc++.h>2 using namespacestd;3 4 Const intMAXN =200000+Ten;5 intA[MAXN], L[MAXN], R[MAXN];6 7map<int,int>cur;8 9InlineBOOLOkintPosintLintR)Ten{returnL[pos] < L && R[pos] >R;} One A BOOLSolveintLintR) - { - if(L >= R)return true; the for(inti =0; L+i <= r-i; i++) - { - if(OK (L+i, L, R))returnSolve (L, l+i-1) && Solve (l+i+1, R); - Else if(OK (R-i, L, R))returnSolve (L, r-i-1) && Solve (r-i+1, R); + } - return false; + } A at intMain () - { - //freopen ("In.txt", "R", stdin); - - intT scanf"%d", &T); - while(t--) in { - intN scanf"%d", &n); to for(inti =0; I < n; i++) scanf ("%d", &a[i]); + cur.clear (); - for(inti =0; I < n; i++) the { *L[i] = Cur.count (A[i])? Cur[a[i]]:-1; $Cur[a[i]] =i;Panax Notoginseng } - cur.clear (); the for(inti = n1; I >=0; i--) + { AR[i] = Cur.count (A[i])?Cur[a[i]]: n; theCur[a[i]] =i; + } - $printf"%s\n", Solve (0, N-1) ?"non-boring":"Boring"); $ } - - return 0; the}code June
UVa 1608 (meet halfway) non-boring sequences