gmo61520

Untitled

Apr 28th, 2016
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. from collections import defaultdict, namedtuple
  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 = 0):
  13. n = tr[id]
  14. nbd[d].append(n)
  15.  
  16. if n[2]:
  17. bd(n[2], nbd, d + 1)
  18. if n[3]:
  19. bd(n[3], nbd, d + 1)
  20.  
  21. nbd = defaultdict(list)
  22. bd(root, nbd)
  23.  
  24. # calculating
  25. res = 0
  26. for nodes in nbd.values():
  27. lb = None
  28. lw = None
  29. for n in nodes:
  30. if n[4] == 1:
  31. ln, lb = lb, n
  32. else:
  33. ln, lw = lw, n
  34. if ln != None and ln[1] == n[1]:
  35. res += 1
  36.  
  37. # output result
  38. print(res)
Advertisement
Add Comment
Please, Sign In to add comment