(UVA - 1608)Non-boring sequences
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)的。输入一个n(n<=200000)个元素的序列A(各个元素均为 109 以内的非负整数),判断它是不是不无聊的。
思路:分治法。不难想到整体思路,在整个序列中找一个只出现过一次的元素,如果不存在,则这个序列不是不无聊的;如果找到一个只出现一次的元素A[p],那么包含元素A[p]的区间都是满足要求的,则只需检查A[1…p-1]和A[p+1…n]是否满足条件。我们在预处理出每个元素左边和右边最近的相同元素的位置,就可以在O(1)时间内判断在任意一个连续子序列中,某个元素是否唯一。如果从左边往右边找,最坏的情况是唯一元素在最后一个元素,此时时间复杂度为O( n2 )。所以我们从两边往中间找,此时的最坏情况是唯一元素在中间的情况,时间复杂度为O( nlogn )。
#include<cstdio>
#include<map>
using namespace std;
const int maxn=200005;
int a[maxn],left[maxn],right[maxn];
map<int,int> mp;
bool unique(int x,int l,int r)//判断x在区间[l,r]是否唯一
{
return left[x]<l&&right[x]>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(l+d==r-d) return false;
if(unique(r-d,l,r)) return check(l,r-d-1)&&check(r-d+1,r);
}
return false;
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
mp.clear();
for(int i=0;i<n;i++)//每个元素左边最近的与该元素相同的元素位置
{
scanf("%d",a+i);
if(!mp.count(a[i])) left[i]=-1;
else left[i]=mp[a[i]];//mp[i]表示a[i]元素所在的位置
mp[a[i]]=i;
}
mp.clear();
for(int i=n-1;i>=0;i--)//每个元素右边最近的与该元素相同的元素位置
{
if(!mp.count(a[i])) right[i]=n;
else right[i]=mp[a[i]];
mp[a[i]]=i;
}
if(check(0,n-1)) printf("non-boring\n");
else printf("boring\n");
}
return 0;
}