Description
We were afraid of making this problem statement too boring, so we decided to keep it short. A sequence
is called non-boring if its every connected subsequence contains a unique element, i.e. an element such
that no other element of that subsequence has the same value.
Given a sequence of integers, decide whether it is non-boring.
Input
The first line of the input contains the number of test cases T. The descriptions of the test cases follow:
Each test case starts with an integer n (1 ≤ n ≤ 200000) denoting the length of the sequence. In
the next line the n elements of the sequence follow, separated with single spaces. The elements are
non-negative integers less than 109
.
Output
Print the answers to the test cases in the order in which they appear in the input. For each test case
print a single line containing the word ‘non-boring’ or ‘boring’.
Sample Input
4
5
1 2 3 4 5
5
1 1 1 1 1
5
1 2 3 2 1
5
1 1 2 1 1
Sample Output
non-boring
boring
non-boring
boring
題目大意:
給你一個數字序列,如果它的每一個連續子串都包含不重複的數字,那麼則稱之爲non-boring。
分析:
1.如果整個序列中存在只出現過一次的數字,那麼所有包含這個數字的子串都是滿足要求的,因此我們只需要檢驗該數字的左邊區間和右邊區間是否滿足條件;
2.如果我們預記錄下每個元素左邊和右邊最近的相同元素的位置,那麼我們就可以O(1)的時間裏判斷該元素在區間內是否唯一存在;
3.如果從左往右找,最壞的情況是需要遍歷整個區間。採用從兩邊向中間找。
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<map>
#include<queue>
using namespace std;
typedef long long LL;
const int maxn = 200002;
int b[maxn][2];//左右最近的相同的數的下標
int a[maxn];
map<int, int >mp;//該元素最後一次出現的下標
bool unique(int i, int l, int r) {
return b[i][0]<l&&b[i][1]>r;
}
bool check(int l, int r) {
if (l >= r) return true;
for (int d = 0; l + d <= r - d; d++) {
if (unique(l + d, l, r))
return check(l, l + d - 1) && check(l + d + 1, r);
if(unique(r-d,l,r))
return check(l, r - d - 1) && check(r - d + 1, r);
if (2 * d == r - l)//如果始終沒有找到unique的元素,那麼return false
return false;
}
return false;
}
int main() {
#ifdef _DEBUG
freopen("liu.in", "r", stdin);
#endif
int T; scanf("%d", &T);
while (T--) {
int n; scanf("%d", &n);
//{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{
//利用map和數組記錄每個元素最近的相同元素的下標
mp.clear();
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
if (!mp.count(a[i]))
b[i][0] = -1;
else
b[i][0] = mp[a[i]];
mp[a[i]] = i;
}
mp.clear();
for (int i = n - 1; i >= 0; i--) {
if (!mp.count(a[i]))
b[i][1] = n;
else
b[i][1] = mp[a[i]];
mp[a[i]] = i;
}
//}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
puts(check(0, n - 1) ? "non-boring" : "boring");
}
return 0;
}