After checking the output of both the debug examples and testcases from the forum I've decided to submit my code to the judge. The problem is Tree Summing, my idea is to use the tree's own nested structure, so one just needs to format the string and use eval. After getting a List it's pretty easy to check whether there's a solution or not. My suspicion is that the RE might be caused by the eval command, or is it some tricky testcase?
import re
def updateStack(string, stack):
for i in string:
if i == '(':
stack += 1
elif i == ')':
stack -= 1
return stack
def inputScan(string, s):
stack = updateStack(string, s)
if stack == 0:
return string
else:
new = input()
return string + inputScan(new, stack)
def traverse(T, num):
if len(T) == 0:
return False
elif len(T[1]) + len(T[2]) == 0:
return T[0] == num
return traverse(T[1], num - int(T[0])) or traverse(T[2], num - int(T[0]))
while True:
try:
input_ = input()
except EOFError:
break
num, treeInput = input_.split(" ", 1)
treeInput = inputScan(treeInput, 0)
str2List = treeInput.replace("(",",[").replace(")","]")
pattern = re.compile(r's+')
str2List = re.sub(pattern, '', str2List)[1:]
Tree = eval(str2List)
f = lambda x: "yes" if x == True else "no"
print(f(traverse(Tree, int(num))))
Tested inputs:
22 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
20 (5(4(11(7()())(2()()))()) (8(13()())(4()(1()()))))
10 (3
(2 (4 () () )
(8 () () ) )
(1 (6 () () )
(4 () () ) ) )
5 ()
0 ()
-1 (-1()())
77 (77(1()())())
-77 (-77()())
-7 (1 (-6 (2 (1 ()()) (-4 ()(1 (1 ()())(-1 ()())
) ) )
() ) () )
0 ()
3 (3 (4 (5 ()()) (8 (-3 (-7 ()())())(-4 ()(-8 ()()))))
(6 (6 (-5 ()())(-6 ()(-9 ()())))(7 ()())))
0 (1()
(-2 () (1()())))
1 (1 () (0 ()()) )
0 (0 ()())
8 (8(2(1()())())())
8 (8(3(7()())())())
4 (4(2(4()())())())
5 (5(4()(1(7(3()())(4()()))(4(3()())())))())
21 (7()(5()(5()(4(1(7()())())()))))
47 (7(9()(1(4()(7()(5(9(3(4(10()())())())(5(9(5(6(3(1(9()(2(3()(9(1(3(7()())(9()()))(9(5()(2()()))()))(7()())))(5(2()(6()(2()())))())))())(7()(2()(3()()))))(9()(10(4()(3()(4(3()(5()()))())))())))(3()()))())()))(6(10()())()))))()))())
24 (9()(6()(1(2(9(8(7()())(1(1(7()())())(8()())))())(6(5(9()())())()))())))
15 (8()(3(7(4(4()(9(6(3(3()())(9(3(3(8()())(7()()))())()))(3()()))()))())())(3(1(8(5(4(2()(4()(3(1()(10()(9()())))())))())(2()()))())())())))
18 (4(9()())(1()(4()(9(3(9()(7()(8(6()())(5()(5()())))))(8(4()(1()()))()))()))))
38 (5
(6
(4
()()
)
(3
()()
)
)
(7
(2
(1
()()
)
(10
()
(9
(5
()()
)
(2
()()
)
)
)
)
()
)
)
Output:
yes
no
yes
no
no
yes
no
yes
yes
no
yes
yes
yes
yes
no
no
no
no
no
no
no
no
no
yes
Aucun commentaire:
Enregistrer un commentaire