fork download
  1. from sys import stdin
  2.  
  3. def getParent(x):
  4. if parent_dict[x] == x:
  5. return x
  6. parent_dict[x] = getParent(parent_dict[x])
  7. return parent_dict[x]
  8.  
  9. def unionParent1(a, b):
  10. a = getParent(a)
  11. b = getParent(b)
  12. sum = cnt_dict[a] + cnt_dict[b]
  13. cnt_dict[a] = sum
  14. cnt_dict[b] = sum
  15. #더 작은 쪽을 부모로 갖는다
  16. if a > b:
  17. parent_dict[a] = b
  18. else:
  19. parent_dict[b] = a
  20. return
  21.  
  22. def unionParent2(a, b): #a가 b의 부모인 것을 전제로 할 때
  23. a = getParent(a)
  24. b = getParent(b)
  25. if a != b:
  26. parent_dict[b] = a
  27. cnt_dict[a] += cnt_dict[b]
  28. return
  29.  
  30. t = int(stdin.readline()) #number of test cases
  31. for i in range(t):
  32. f = int(stdin.readline()) #number of friendships formed
  33. #부모를 저장하는 딕셔너리와 같은 네트워크 친구 수를 저장하는 딕셔너리
  34. parent_dict, cnt_dict = dict(), dict()
  35. for j in range(f):
  36. name1, name2 = stdin.readline().split()
  37. #입력받은 이름이 딕셔너리에 없는 경우 저장
  38. if name1 not in parent_dict:
  39. parent_dict[name1] = name1
  40. cnt_dict[name1] = 1
  41. if name2 not in parent_dict:
  42. parent_dict[name2] = name2
  43. cnt_dict[name2] = 1
  44. #부모를 합친다
  45. #unionParent2(name1, name2)
  46. unionParent1(name1, name2) #이 함수를 이용하면 출력초과가 뜬다
  47.  
  48. #같은 네트워크의 친구 수를 출력
  49. print(cnt_dict[getParent(name1)])
Success #stdin #stdout 0.02s 9316KB
stdin
1
10
a b
a c
a d
a e
b c
b d
b e
c d
c e
d e
stdout
2
3
4
5
10
20
40
80
160
320