您的位置:首页 > 产品设计 > UI/UE

UVA - 1608 Non-boring sequences 递归,分治

2017-08-25 16:54 363 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva 递归 分治