UVa 1608 Non-boring sequence (分治)

本文介绍了一种高效算法,用于判断整数序列是否为不无聊序列,即任意连续子序列都至少含有一个唯一元素。通过预处理序列,可在O(1)时间内查找特定元素,递归验证左右子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://vjudge.net/problem/UVA-1608

题意:给出一个整数序列,若序列的任意一个连续子序列都至少有一个只出现一次的元素,则该序列为不无聊序列。判断一个序列是否无聊。

思路:若某个元素在整个序列中只出现一次,则所有包含该元素的连续子序列都为不无聊序列。因此,找到这样一个元素后,只需判断该元素左边与右边的序列是否为无聊序列即可。 怎么找到这样的元素呢?可以对每个序列预先处理出其左边及其右边第一个和它相同的值得位置,这样就可以在O(1)的复杂度内判断了。


#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
typedef long long LL;
using namespace std;
typedef pair<int, int> P;
const int INF = 1e8 + 10;
const int maxn = 1e5 + 10;
map<int, int> mp;
int a[maxn], n;
int pre[maxn], after[maxn];

bool judge(int L, int R, int p)
{
    return pre[p] < L && after[p] > R;
}


bool solve(int L, int R)
{
    if(L >= R) return true;
    int i = L, j = R;
    while(i <= j && (i <= R || j >= L))
    {
        if(i <= R && judge(L, R, i)) return solve(L, i-1) && solve(i+1, R);
        if(j >= L && judge(L, R, j)) return solve(L, j-1) && solve(j+1, R);
        i++, j--;
    }
    return false;
}

int main() {
  int T;
  scanf("%d", &T);
  while(T--)
  {
      mp.clear();
      scanf("%d", &n);
      for(int i = 1; i <= n; i++)
      {
          scanf("%d", &a[i]);
          if(mp.count(a[i]))
          {
              pre[i] = mp[a[i]];
              after[mp[a[i]]] = i;
          }
          else
          {
              pre[i] = -1;
              after[i] = n+1;
          }
          mp[a[i]] = i;
      }
      if(solve(1, n)) printf("non-boring\n");
      else printf("boring\n");
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值