UVa 1608:Non-boring swquences(分治)

1 篇文章 0 订阅

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=844&page=show_problem&problem=4483

题意:如果一个序列的任意连续子序列中至少有一个只出现一次的元素,则称这个序列式不无聊(non-boring)的。输入一个n (n200000) 个元素的序列A(各个元素均为 109 以内的非负整数),判断它是不是不无聊的。(本段摘自《算法竞赛入门经典(第2版)》

分析:
首先预处理每个元素向左向右分别能延伸到什么地方,然后采用分治的思想,对于一段序列,首先去寻找只出现一次的元素,假设为a[i],然后分别递归处理a[i]左边和右边的序列,处理完即可。
需要注意的是,在寻找只出现一次的元素是,要从两边同时开始找,这样最坏情况的复杂度为 O(nlogn) ,如果只从一边找的话,最坏情况复杂度为 O(n2)

代码:

#include <fstream>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <sstream>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <string>
#include <vector>

using namespace std;

const int maxn = 200000 + 5;

int T, n;
int a[maxn], l[maxn], r[maxn], pos[maxn];

bool DFS(int L, int R)
{
    if (L + 1 >= R)
        return true;
    for (int i = L; i < R; ++i)
    {
        if (l[i] < L && r[i] >= R)
            return DFS(L, i) && DFS(i + 1, R);
        if (l[R - (i - L) - 1] < L && r[R - (i - L) - 1] >= R)
            return DFS(L, R - (i - L) - 1) && DFS(R - (i - L) - 1 + 1, R);
    }
    return false;
}

int main()
{
    scanf("%d", &T);
    for (int C = 0; C < T; ++C)
    {
        scanf("%d", &n);
        for (int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        for (int i = 0; i < n; ++i)
            pos[i] = -1;
        for (int i = 0; i < n; ++i)
        {
            l[i] = pos[a[i]];
            pos[a[i]] = i;
        }
        for (int i = 0; i < n; ++i)
            pos[i] = n;
        for (int i = n - 1; i >= 0; --i)
        {
            r[i] = pos[a[i]];
            pos[a[i]] = i;
        }
        if (DFS(0, n))
            printf("non-boring\n");
        else
            printf("boring\n");
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值