gmo61520

Untitled

Apr 28th, 2016
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. from collections import defaultdict
  2. # values: id, key, child labels (left and right), color
  3.  
  4. # parsing input
  5. nc, root = map(int, input().split())
  6. tr = {}
  7. for n in range(nc):
  8. n = list(map(int, input().split()))
  9. tr[n[0]] = n
  10.  
  11. # building depths
  12. def bd(id, d):
  13. global nbd
  14.  
  15. n = tr[id]
  16. nbd[d].append(n)
  17.  
  18. if n[2]:
  19. bd(n[2], d + 1)
  20. if n[3]:
  21. bd(n[3], d + 1)
  22.  
  23. nbd = defaultdict(list)
  24. bd(root, 0)
  25.  
  26. # calculating
  27. res = 0
  28. for nodes in nbd.values():
  29. lb = None
  30. lw = None
  31. for n in nodes:
  32. if n[4] == 1:
  33. ln, lb = lb, n
  34. else:
  35. ln, lw = lw, n
  36. if ln != None and ln[1] == n[1]:
  37. res += 1
  38.  
  39. # output result
  40. print(res)
Advertisement
Add Comment
Please, Sign In to add comment