Description
我们害怕把这道题题面搞得太无聊了,所以我们决定让这题超短。一个序列被称为是不无聊的,仅当它的每个连续子序列存在一个独一无二的数字,即每个子序列里至少存在一个数字只出现一次。给定一个整数序列,请你判断它是不是不无聊的。
Input
第一行一个正整数T,表示有T组数据。每组数据第一行一个正整数n,表示序列的长度,1 <= n <= 200000。接下来一行n个不超过10^9的非负整数,表示这个序列。
Output
对于每组数据输出一行,输出”non-boring”表示这个序列不无聊,输出”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
思路
我们可以把相同的数字用双向链表串起来,pre[x]为x位置之前第一个和x位置数字相同的位置,nexx为x位置之后第一个和x位置数字相同的位置。对于区间[l,r],当存在位置x使
prex<l且nexx>r
。则这个区间是不无聊的,而且区间[l,r]的所有包含x位置的子区间也是不无聊的,所以可以递归判断区间[l,x−1]和[x+1,r]。
对于区间[l,r],如果按l~r的顺序枚举满足
prex<l且nexx>r
的位置x,那么最坏的情况下,位置x在位置r处。这样就会向下递归n层。时间复杂度O(
N2
)。
而如果对于区间[l,r],从两边向中间枚举,那么最坏的情况下,位置x在位置l+r2处,
这样会向下递归logn层,时间复杂度O(nlogn)。
那么再加个map应该是O(
nlog2n
)。
鸣谢zp1ng大佬时间复杂度证明
#include <bits/stdc++.h>
using namespace std;
inline int read(){
int ret=0,f=1;char c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())ret=(ret<<3)+(ret<<1)+c-'0';
return ret*f;
}
int n,a[200005],ne[200005],la[200005],b[200005];
map<int,int>q;
bool check(int x,int y){
if(x>y)return 1;
int xx=x,yy=y;
while(xx<=yy){
if(la[xx]<x&&ne[xx]>y)return check(x,xx-1)&&check(xx+1,y);
++xx;
if(la[yy]<x&&ne[yy]>y)return check(x,yy-1)&&check(yy+1,y);
--yy;
}
return 0;
}
int main(){
int T=read();
while(T--){
n=read();
for(int i=1;i<=n;++i){
a[i]=read();
}
q.clear();
for(int i=1;i<=n;++i){
if(q.find(a[i])==q.end())la[i]=0;
else la[i]=q[a[i]];
q[a[i]]=i;
}
q.clear();
for(int i=n;i;--i){
if(q.find(a[i])==q.end())ne[i]=n+1;
else ne[i]=q[a[i]];
q[a[i]]=i;
}
printf(check(1,n)==true?"non-boring\n":"boring\n");
}
return 0;
}