Great Vova Wall

问题: Great Vova Wall 

Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.

The current state of the wall can be respresented by a sequence 𝑎a of 𝑛n integers, with 𝑎𝑖ai being the height of the 𝑖i-th part of the wall.

Vova can only use 2×12×1 bricks to put in the wall (he has infinite supply of them, however).

Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some 𝑖i the current height of part 𝑖iis the same as for part 𝑖+1i+1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 11 of the wall or to the right of part 𝑛n of it).

The next paragraph is specific to the version 1 of the problem.

Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.

Vova is a perfectionist, so he considers the wall completed when:

  • all parts of the wall has the same height;
  • the wall has no empty spaces inside it.

Can Vova complete the wall using any amount of bricks (possibly zero)?

Input

The first line contains a single integer 𝑛n (1𝑛21051≤n≤2⋅105) — the number of parts in the wall.

The second line contains 𝑛n integers 𝑎1,𝑎2,,𝑎𝑛a1,a2,…,an (1𝑎𝑖1091≤ai≤109) — the initial heights of the parts of the wall.

Output

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).

Print "NO" otherwise.

题解:

  1. 这个问题通过对数组中每个数作+2*n操作转化为01串,即默认偶数为0奇数为1,后续的操作都是对这个01串操作;

  2.通过观察可以发现,任意相邻的两个0(’00‘)或者两个1(’11‘)可以达到任意的高度,即对整个最终数组达到的高度不起决定作用;

  3.所以问题就转化成去掉该01串中相邻的00或者11,直到该数组只剩一个元素(奇数个元素)或者为空(偶数个元素);

  4.如果直接遍历该列表,去掉其中的相邻的00或者11,必然会使00或者11左右两边的状态发生变化,产生新的00或者11,故需要多次检测;

  5.这里我引入栈,从头开始遍历一遍列表,一次就可以检测出最终结果,(也可以使用链表,需要对链表的删除做操作)。

代码:

def wall(n, a):
    a = [0 if x%2 == 0 else 1 for x in a]
    stack = [a[0]]
    append = stack.append
    pop = stack.pop
    for i in range(1, n):
        if len(stack) > 0:
            ele = stack[-1]
            if ele == a[i]:
                pop()
        else:
            append(a[i])
    return len(stack) <= 1

n = int(input())
a = map(int, input().split())
res = wall(n, a)
print('YES' if res else 'NO')

 

 

posted @ 2019-01-01 12:07  WoodSimple  阅读(163)  评论(0)    收藏  举报