fork(1) download
  1. import collections
  2.  
  3. def find(A):
  4. global root
  5. a=collections.deque([A])
  6. route=[]
  7. while a:
  8. b=a.popleft()
  9. route.append(b)
  10. if b==root[b]:
  11. for i in route:
  12. root[i]=b
  13. # print(root)
  14. return b
  15. a.append(root[b])
  16.  
  17.  
  18. N,M=map(int,input().split())
  19. root=[i for i in range(N+1)] # 자기자신을 부모로
  20. for _ in range(M):
  21. x,a,b=map(int,input().split())
  22. if x ==0:# 합
  23. root[a]=min(root[a],root[b])
  24. root[b]=min(root[a],root[b])
  25. # print(root)
  26. else:
  27. # print(root)
  28. if find(a)==find(b):
  29. print('YES')
  30. else:
  31. print('NO')
  32. print(root)
Success #stdin #stdout 0.01s 27712KB
stdin
5 5
0 1 3
0 4 5
0 2 5
0 2 3
1 1 5
stdout
YES
[0, 1, 1, 1, 4, 1]