UVA 1608 Non-boring sequences

e 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 rst 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 10
9
.
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
‘.
SampleInput
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
SampleOutput
non-boring
boring
non-boring
boring

解题思路:采用分治的方法,假设原先数组中存在一个仅出现一次的数,假设其位置为p,则我们容易知道包含p的所有区间均是non-bor的。我们只需要判断[1,p-1]和[p+1,n]其相应的子区间即可。其中我们判断在某一个区间内某一个数是否出现一次的时候,我们只需要判断和他相同且距离其最近的左边和右边的数是否在此区间内即可,这个我们通过预处理出L[i]和R[i]。另外为了避免分治过程中出现极端化的情况,我们在区间内寻找该元素的时候从两端向中间寻找,这样我们的极限情况便为T(n)=2*T(n/2)+O(n),易知其复杂度为O(nlogn),因此算法总的复杂度为O(nlogn)。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 200010;
int arr[maxn];
int L[maxn], R[maxn];
map<int,int> mp;

bool solve(int l, int r) {
    if(l >= r) return true;
    int i = l, j = r, p = -1;
    while(i <= j) {
        if((L[i]1)&&(R[i]>r||R[i]==-1)) {
            p = i;
            break;
        }
        if((L[j]==-1||L[j]1||R[j]>r)) {
            p = j;
            break;
        }
        ++i, --j;
    }
    if(p == -1) return false;
    return solve(l, p - 1) && solve(p + 1, r);
}

int main() {

    //freopen("aa.in", "r", stdin);

    int T, n;
    scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &arr[i]);
        }
        //memset(L, -1, sizeof(L));
        //memset(R, -1, sizeof(R));
        mp.clear();
        L[1] = -1;
        mp[arr[1]] = 1;
        for(int i = 2; i <= n; ++i) {
            if(mp.find(arr[i]) != mp.end()) {
                L[i] = mp[arr[i]];
            } else {
                L[i] = -1;
            }
            mp[arr[i]] = i;
        }
        mp.clear();
        R[n] = -1;
        mp[arr[n]] = n;
        for(int i = n - 1; i >= 1; --i) {
            if(mp.find(arr[i]) != mp.end()) {
                R[i] = mp[arr[i]];
            } else {
                R[i] = -1;
            }
            mp[arr[i]] = i;
        }
        if(solve(1, n)) {
            printf("non-boring\n");
        } else {
            printf("boring\n");
        }
    }
    return 0;
}

你可能感兴趣的:(UVA)