Hi, I’m trying to solve IMPER (https://www.spoj.com/problems/IMPER/) problem. I’m not sure why I’m getting NZEC with
this code. It works fine on the problem test cases and on the udebug ones.
def getDiameter(graph):
last = 2
dist = {}
def dfs(curr):
nonlocal last
nonlocal dist
try:
for v in graph[curr]:
if v not in dist:
dist[v] = dist[curr] + 1
if dist[v] > dist[last]:
last = v
dfs(v)
except:
print("blabla")
dist[2] = 0
dfs(2)
dist = {}
dist[last] = 0
dfs(last)
return dist[last]
out = []
while True:
n = int(input())
if n == -1:
break
A = input().split()
A = [int(x) for x in A]
graph = {}
for i in range(len(A)):
if A[i] not in graph:
graph[A[i]] = []
if i + 2 not in graph:
graph[i + 2] = []
graph[A[i]].append(i + 2)
graph[i + 2].append(A[i])
out.append(getDiameter(graph) + 1)
for x in out:
print(x//2)
I added a try/except block to debug, and found that the error is between lines 10-17, but I still got no clue what is happening… Can someone help me?
Thanks!