Indialbedo's blog

By Indialbedo, history, 3 years ago, In English

have a look at this code of 1565E which got runtime error and idk why, so I have to write again in C++ during the competition.

I'll appreciate if somebudy could do me a favor :)

import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def rdvec():
  return [int(i) for i in input().split()]
def rd():
  return int(input())
T=int(input())
def solve():
  n=rd()
  g=[[] for i in range(n)]
  U=[0]*n
  for i in range(n-1):
    x,y=rdvec()
    x-=1
    y-=1
    g[x].append(y)
    g[y].append(x)
    U[x]+=1
    U[y]+=1
  def dfs(x,fa,s):
    if s%2==0:
      U[x]=-U[x]
    for y in g[x]:
      if y!=fa:
        dfs(y,x,s+1)
  dfs(0,0,0)
  print(*U)
for o in range(T):
  solve()
  • Vote: I like it
  • +6
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it +29 Vote: I do not like it

You cannot call any function recursively more than 1000 times in python unless you increase the recursion limit. So, it would only work for n < 1000 while the limit for n is 10^5. So do this to your submission.

»
3 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

You can also do your DFS iteratively, by using an array as a stack:

todo = [(0,0,0)]
while len(todo) > 0:
    x, fa, s = todo.pop()
    if s%2 == 0:
        U[x]=-U[x]
    for y in g[x]:
        if y != fa:
            todo.append((y, x, s+1))  # this is still a DFS, but different order

Full submission: 151374138 (Compare memory usage to FrozenKandy's version)