Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false. 

Implication is written by using character '$\rightarrow$', and the arguments and the result of the implication are written as '0' (false) and '1' (true). According to the definition of the implication: 

$0 \rightarrow 0 = 1$ 

$0 \rightarrow 1 = 1$

$1 \rightarrow 0 = 0$ 

$1 \rightarrow 1 = 1$

When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,

$0 \rightarrow 0 \rightarrow 0 =(0 \rightarrow 0) \rightarrow 0 = 1 \rightarrow 0 = 0$. 

When there are brackets, we first calculate the expression in brackets. For example,

$0 \rightarrow(0 \rightarrow 0) = 0 \rightarrow 1 = 1$.

For the given logical expression $a_{1} \rightarrow a_{2} \rightarrow a_{3} \rightarrow \cdots \cdots a_{n}$ determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.


-----Input-----

The first line contains integer n (1 ≤ n ≤ 100 000) — the number of arguments in a logical expression.

The second line contains n numbers a_1, a_2, ..., a_{n} ($a_{i} \in \{0,1 \}$), which means the values of arguments in the expression in the order they occur.


-----Output-----

Print "NO" (without the quotes), if it is impossible to place brackets in the expression so that its value was equal to 0.

Otherwise, print "YES" in the first line and the logical expression with the required arrangement of brackets in the second line.

The expression should only contain characters '0', '1', '-' (character with ASCII code 45), '>' (character with ASCII code 62), '(' and ')'. Characters '-' and '>' can occur in an expression only paired like that: ("->") and represent implication. The total number of logical arguments (i.e. digits '0' and '1') in the expression must be equal to n. The order in which the digits follow in the expression from left to right must coincide with a_1, a_2, ..., a_{n}.

The expression should be correct. More formally, a correct expression is determined as follows:  Expressions "0", "1" (without the quotes) are correct.  If v_1, v_2 are correct, then v_1->v_2 is a correct expression.  If v is a correct expression, then (v) is a correct expression. 

The total number of characters in the resulting expression mustn't exceed 10^6.

If there are multiple possible answers, you are allowed to print any of them.


-----Examples-----
Input
4
0 1 1 0

Output
YES
(((0)->1)->(1->0))

Input
2
1 1

Output
NO

Input
1
0

Output
YES
0

Source: codeforces | Difficulty: HARD
Tags: Mathematics

Greedy algorithms

Implementation

Constructive algorithms


Solutions:
from collections import deque

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	S = n - sum(a)
	if a[-1] != 0:
		return ('NO', None)
	if S == 1 and n == 1:
		return ('YES', '0')
	if S == 2 and (a[-1] == a[-2] and a[-1] == 0):
		return ('NO', None)
	return ('YES', make(a))

def insert_head(x, cur):
	cur.appendleft('>')
	cur.appendleft('-')
	cur.appendleft(str(x))
	cur.appendleft('(')
	cur.append(')')

def insert_tail(x, cur):
	cur.append('-')
	cur.append('>')
	cur.append(x)

def make(a):
	cur = None
	for x in a[::-1][1:]:
		if cur is None:
			cur = deque([str(x)])
		else:
			insert_head(x, cur)
	insert_tail(str(a[-1]), cur)
	return ''.join(cur)
(ans, s) = solve()
if ans == 'NO':
	print(ans)
else:
	print(ans)
	print(s)


N = int(input())
A = list(map(int, input().split(' ')))

def write_as_0(A):
	assert len(A)
	if len(A) == 1:
		if A[0] == 0:
			return 0
		if A[0] == 1:
			return False
	if len(A) == 2:
		if A == [1, 0]:
			return (1, 0)
		else:
			return False
	if A[-1] == 1:
		return False
	left = write_as_1(A[:-1])
	if left == False:
		return False
	else:
		return (left, 0)

def write_as_1(A):
	assert len(A)
	if len(A) == 1:
		if A[0] == 1:
			return 0
		if A[0] == 0:
			return False
	if len(A) == 2:
		if A == [1, 0]:
			return False
		else:
			return tuple(A)
	if A[-1] == 1:
		return tuple(A)
	if A[-2] == 0:
		return (tuple(A[:-2]), (0, 0))
	i = len(A) - 2
	while i >= 0 and A[i] == 1:
		i -= 1
	if i == -1:
		return False
	left = tuple(A[:i])
	right = tuple(A[i + 1:])
	if len(left) == 0:
		return (0, right)
	else:
		return (left, (0, right))

def calculate(t):
	if t is False:
		return '-'
	if isinstance(t, int):
		return t
	t = tuple(map(calculate, t))
	if len(t) == 1:
		return calculate(t[0])
	if len(t) == 2:
		if t == (1, 0):
			return 0
		return 1
	else:
		(a, b, *c) = t
		return calculate([calculate([a, b]), calculate(c)])

def binary_sequences(length):
	if length == 0:
		return [[]]
	b = binary_sequences(length - 1)
	b1 = map(lambda x: x + [1], b)
	b0 = map(lambda x: x + [0], b)
	return list(b0) + list(b1)

def to_impl(t):
	if isinstance(t, int):
		return str(t)
	else:
		t = map(to_impl, t)
		return '(' + '->'.join(t) + ')'
ans = write_as_0(A)
if ans is False:
	print('NO')
else:
	print('YES')
	print(to_impl(ans))


def f(a):
	if len(a) == 1:
		if a[0] == 0:
			print('YES\n0')
			return
		else:
			print('NO')
			return
	if a[-1] == 1:
		print('NO')
		return
	if a[-2] == 1:
		print('YES')
		print('->'.join((str(x) for x in a)))
		return
	elif len(a) == 2:
		print('NO')
		return
	elif len(a) >= 3 and a[-3] == 0:
		a[-3] = '(0'
		a[-2] = '0)'
		print('YES\n' + '->'.join((str(x) for x in a)))
		return
	for i in range(len(a) - 3, -1, -1):
		if a[i] == 0:
			a[i] = '(' + str(a[i])
			a[i + 1] = '(' + str(a[i + 1])
			a[-2] = '0))'
			print('YES\n' + '->'.join((str(x) for x in a)))
			return
	print('NO')
	return
n = int(input())
a = list((int(x) for x in input().split()))
f(a)


x = int(input())
seq = list(map(int, input().split(' ')))
if seq == [0]:
	print('YES')
	print(0)
elif seq == [0, 0]:
	print('NO')
elif seq == [1, 0]:
	print('YES')
	print('1->0')
elif seq == [0, 0, 0]:
	print('YES')
	print('(0->0)->0')
elif seq == [1, 0, 0]:
	print('NO')
elif seq[x - 1] == 1:
	print('NO')
elif seq[x - 2] == 1:
	print('YES')
	print('->'.join([str(x) for x in seq]))
elif seq == [1] * (x - 2) + [0, 0]:
	print('NO')
elif seq[x - 3] == 0:
	a = '->'.join([str(x) for x in seq][0:x - 3])
	print('YES')
	print(a + '->(0->0)->0')
else:
	last = 0
	for i in range(x - 1):
		if seq[i] == 0 and seq[i + 1] == 1:
			last = i
	seq[last] = '(0'
	seq[last + 1] = '(1'
	seq[x - 2] = '0))'
	print('YES')
	print('->'.join([str(x) for x in seq]))


import sys
input = []
input_index = 0

def next(type, number=None):

	def next():
		global input, input_index
		while input_index == len(input):
			if sys.stdin:
				input = sys.stdin.readline().split()
				input_index = 0
			else:
				raise Exception()
		input_index += 1
		return input[input_index - 1]
	if number is None:
		result = type(next())
	else:
		result = [type(next()) for _ in range(number)]
	return result
n = next(int)
ks = next(str, n)
if ks[-1] == '0':
	if n == 1:
		print('YES')
		print('0')
	elif '0' in ks[:-2] or ks[-2] != '0':
		print('YES')
		for k in ks[:-2]:
			sys.stdout.write(k + '->(')
		sys.stdout.write(ks[-2])
		for _ in range(len(ks) - 2):
			sys.stdout.write(')')
		sys.stdout.write('->0\n')
		sys.stdout.flush()
	else:
		print('NO')
else:
	print('NO')


n = int(input())
s = input().split()
t = []
j = -1
for i in range(n):
	t += [int(s[i])]
	if int(s[i]) == 1:
		j = i
if t[n - 1] == 1:
	print('NO')
elif j == -1:
	if n == 1:
		print('YES')
		print(0)
	elif n == 2:
		print('NO')
	else:
		print('YES')
		for i in range(n - 3):
			print(s[i] + '->', end='')
		print('(0->0)->0')
elif j < n - 3:
	print('YES')
	for i in range(n - 3):
		print(s[i] + '->', end='')
	print('(0->0)->0')
elif j == n - 2:
	print('YES')
	for i in range(n - 1):
		print(s[i] + '->', end='')
	print('0')
else:
	k = -1
	for i in range(n - 2):
		if t[i] == 0:
			k = i
	if k == -1:
		print('NO')
	else:
		print('YES')
		for i in range(k):
			print(s[i] + '->', end='')
		print('(0->(', end='')
		for i in range(n - k - 3):
			print('(', end='')
		for i in range(n - k - 3):
			print('1)->', end='')
		print('0))->0')


n = int(input())
s = ''.join(input().split())
if s == '0':
	print('YES')
	print('0')
elif s[-1] == '1':
	print('NO')
elif s[-2:] == '10':
	print('YES')
	print('->'.join(s))
else:
	pos = s.rfind('0', 0, -2)
	if pos != -1:
		print('YES')
		if pos != 0:
			print('->'.join(s[:pos]), end='->')
		print('(0->(%s))->0' % '->'.join(s[pos + 1:-1]))
	else:
		print('NO')


import math, string, itertools, fractions, heapq, collections, re, array, bisect
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque

def VI():
	return list(map(int, input().split()))

def ret_yes(x):
	print('YES')
	print(x)

def pr(a):
	print(a[0], end='')
	for x in a[1:]:
		print('->{}'.format(x), end='')
	print()

def pr2(a):
	p = 0
	for (i, x) in enumerate(a[:-2]):
		if x == 0:
			print('{}->('.format(x), end='')
			p += 1
		else:
			print('{}->'.format(x), end='')
	print(a[-2], end='')
	for i in range(p):
		print(')', end='')
	print('->{}'.format(a[-1]))

def main(n, a):
	if a[-1] != 0:
		print('NO')
	elif n == 1:
		print('YES')
		print('0')
	elif n == 2 and a[0] == 0:
		print('NO')
	elif a[-2] == 0 and 0 not in set(a[:-2]):
		print('NO')
	elif a[-2] == 1:
		print('YES')
		pr(a)
	else:
		print('YES')
		pr2(a)

def main_input(info=0):
	n = int(input())
	a = VI()
	main(n, a)
main_input()


n = int(input())
arr = list(map(int, input().strip().split(' ')))

class MyExcept(BaseException):
	pass

def left_rec(lst, L, R):
	k = R - L + 1
	ans = '(' * k + ')->'.join(map(str, lst[L:R + 1])) + ')'
	return ans

def solve():
	if arr[-2] == 1:
		return '(' + left_rec(arr, 0, len(arr) - 2) + '->0)'
	elif n == 3:
		if arr[-3] == 0:
			return '((0->0)->0)'
		else:
			raise MyExcept()
	elif arr[-3] == 0:
		return '((' + left_rec(arr, 0, len(arr) - 4) + '->(0->0))->0)'
	else:
		k = 0
		for i in range(0, len(arr) - 3):
			if arr[i] == 0:
				k = i
				break
		else:
			raise MyExcept()
		return '((' + left_rec(arr, 0, k) + '->' + left_rec(arr, k + 1, len(arr) - 2) + ')->0)'

def main():
	if n == 1:
		if arr[0] == 0:
			print('YES')
			print('0')
		else:
			print('NO')
	elif n == 2:
		if arr[0] == 1 and arr[1] == 0:
			print('YES')
			print('(1->0)')
		else:
			print('NO')
	elif arr[-1] == 1:
		print('NO')
	else:
		try:
			s = solve()
			print('YES')
			print(s)
		except MyExcept:
			print('NO')
main()


def constructExpression(a, l, r):
	res = '('
	for i in range(l, r):
		res += a[i] + ('->' if i != r - 1 else ')')
	return str(res)

def allOnes(a, l, r):
	for i in range(l, r):
		if a[i] != '1':
			return False
	return True
N = int(input())
a = [x for x in input().split()]
if len(a) == 1:
	if a[0] == '1':
		print('NO')
	else:
		print('YES')
		print('0')
elif len(a) == 2:
	if a[0] == '1' and a[1] == '0':
		print('YES')
		print('1->0')
	else:
		print('NO')
elif a[len(a) - 1] == '1':
	print('NO')
elif a[len(a) - 2] == '1':
	print('YES')
	print(constructExpression(a, 0, len(a)))
elif allOnes(a, 0, len(a) - 2):
	print('NO')
else:
	index = len(a) - 3
	for i in range(len(a) - 3, -1, -1):
		if a[i] == '0':
			index = i
			break
	a = a[:index + 1] + [constructExpression(a, index + 1, len(a) - 1)] + a[len(a) - 1:]
	a = a[:len(a) - 3] + [constructExpression(a, len(a) - 3, len(a) - 1)] + a[len(a) - 1:]
	print('YES')
	print(constructExpression(a, 0, len(a)))


n = int(input())
c = list(map(int, input().split()))
idx = [i for i in range(n) if c[i] == 0]
one = [i for i in range(n) if c[i] == 1]
if len(idx) >= 1 and idx[-1] == n - 1:
	if len(idx) >= 2 and idx[-2] == n - 2:
		if len(idx) >= 3 and idx[-3] <= n - 3:
			if idx[0] == 0:
				print('YES')
				r = ''
				for i in range(n):
					if i == 1:
						r += '('
					r += str(c[i])
					if i == n - 2:
						r += ')'
					if i != n - 1:
						r += '->'
				print(r)
			else:
				print('YES')
				r = ''
				if idx[-2] - 1 == 0:
					for i in range(n):
						if i == 0:
							r += '('
						r += str(c[i])
						if i == idx[-2] - 1:
							r += ')'
						if i != n - 1:
							r += '->'
				else:
					for i in range(n):
						if i == 0:
							r += '('
						elif i == idx[0]:
							r += '('
						elif i == idx[0] + 1:
							r += '('
						r += str(c[i])
						if i == idx[-1] - 1:
							r += '))'
						elif i == idx[0] - 1:
							r += ')'
						if i != n - 1:
							r += '->'
				print(r)
		else:
			print('NO')
	else:
		print('YES')
		print('->'.join(map(str, c)))
else:
	print('NO')


n = int(input())
a = list(input().split())
if a[-1] > '0' or (len(a) > 1 and a.count('0') == 2 and (a[-1] < '1') and (a[-2] < '1')):
	print('NO')
else:
	if len(a) > 1:
		if a[-2] < '1':
			a[-2] += '))'
			b = a[:-2]
			b.reverse()
			p = len(a) - 3 - b.index('0')
			a[p] = '(' + a[p]
			a[p + 1] = '(' + a[p + 1]
	print('YES')
	print('->'.join(a))


n = int(input())
v = input().split()
if v[-1] != '0':
	print('NO')
else:
	if n >= 2 and v[-2] == '0':
		for i in range(n - 3, -1, -1):
			if v[i] == '0':
				v[i] = '(' + v[i]
				v[i + 1] = '(' + v[i + 1]
				v[-2] = v[-2] + '))'
				break
		else:
			print('NO')
			exit()
	print('YES')
	print('->'.join(v))