Advertisement
serega1112

Bipartition

Mar 6th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1.  
  2. n, m = map(int, input().split())
  3.  
  4. edges = []
  5. while m:
  6.     edges.append(list(map(int, input().split())))
  7.     m -= 1
  8.  
  9. g = dict()
  10.  
  11. for v in range(1, n + 1):
  12.     g[v] = []
  13.  
  14. for a, b in edges:
  15.     g[a].append(b)
  16.     g[b].append(a)
  17.  
  18. visited = [0] * (n + 1)
  19. res = 'YES'
  20. for v in g:
  21.     if not visited[v]:
  22.         st = [v]
  23.         visited[v] = 1
  24.         while st:
  25.             cur = st.pop()
  26.             color = 2 if visited[cur] == 1 else 1
  27.             for nb in g[cur]:
  28.                 if visited[nb] == 0:
  29.                     st.append(nb)
  30.                     visited[nb] = color
  31.                 elif visited[nb] != color:
  32.                     res = 'NO'
  33.  
  34. print(res)
  35. if res == 'YES':
  36.     print(' '.join([str(i) for i, c in enumerate(visited) if c == 2]))
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement