UVa 1608:Non-boring swquences(分治)
2015-08-30 13:38
344 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=844&page=show_problem&problem=4483
题意:如果一个序列的任意连续子序列中至少有一个只出现一次的元素,则称这个序列式不无聊(non-boring)的。输入一个n(n≤200000)(n \le 200000)个元素的序列A(各个元素均为10910^9以内的非负整数),判断它是不是不无聊的。(本段摘自《算法竞赛入门经典(第2版)》
分析:
首先预处理每个元素向左向右分别能延伸到什么地方,然后采用分治的思想,对于一段序列,首先去寻找只出现一次的元素,假设为a[i],然后分别递归处理a[i]左边和右边的序列,处理完即可。
需要注意的是,在寻找只出现一次的元素是,要从两边同时开始找,这样最坏情况的复杂度为O(nlogn)O(nlogn),如果只从一边找的话,最坏情况复杂度为O(n2)O(n^2)。
代码:
题意:如果一个序列的任意连续子序列中至少有一个只出现一次的元素,则称这个序列式不无聊(non-boring)的。输入一个n(n≤200000)(n \le 200000)个元素的序列A(各个元素均为10910^9以内的非负整数),判断它是不是不无聊的。(本段摘自《算法竞赛入门经典(第2版)》
分析:
首先预处理每个元素向左向右分别能延伸到什么地方,然后采用分治的思想,对于一段序列,首先去寻找只出现一次的元素,假设为a[i],然后分别递归处理a[i]左边和右边的序列,处理完即可。
需要注意的是,在寻找只出现一次的元素是,要从两边同时开始找,这样最坏情况的复杂度为O(nlogn)O(nlogn),如果只从一边找的话,最坏情况复杂度为O(n2)O(n^2)。
代码:
#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; }
相关文章推荐
- CEGUI编译
- EasyUI常用控件禁用方法
- UIimage View
- UIButton状态:添加图片:
- 剖析安卓build系统的设计思想以及案例模拟
- iphone开发之表格组件UITableView的使用(二)如何分组展示数据并添加组头和组尾描述
- easyui使用mergeCells合并单元格后第一行行高过大
- iOS开发 - UIAlertController 弹框提醒
- 考评系统学到的UI设计理念
- UIWindow和UIView
- UI设计规范
- iOS8新特性(2)——UIPopoverController和UIPresentationController
- iOS8新特性(1)——UIAlertController
- 编写广播时出现Exported receiver does not require permission
- 学习YUI.Ext 第一天:EXT简介(一)
- HOWTO: Install, Build and Use openCV (MacOSX 10.10)
- POJ 2524 Ubiquitous Religions(宗教种类:并差集)
- adbd cannot run as root in production builds
- iphone开发之表格组件UITableView的使用(一)使用时的具体步骤介绍
- UUID.randomUUID().toString 简单解释