Advertisement
Hrispens

Задача "Починить Интернет"

Mar 22nd, 2023
724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | Jokes | 0 0
  1. #data1 has an answer of 46 https://pastebin.com/GY523XGA
  2. #data has an answer of 82 https://pastebin.com/pkJsfPg3
  3.  
  4. from collections import defaultdict
  5.  
  6. edges = []
  7. graph = {}
  8. f = open("data1.txt", "r")
  9. m = int(f.readline())
  10. for line in f:
  11.     edge = line.split(" ")
  12.     edge = list(map(lambda item: int(item), edge))
  13.     if len(edge) == 1:
  14.         edge.append(None)
  15.     edges.append(edge)
  16.  
  17.  
  18.  
  19. # graph = dict.fromkeys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], )
  20. graph = dict.fromkeys(range(1, m + 1), )
  21. print(edges)
  22.  
  23. i = 1
  24.  
  25. for edge in edges:
  26.     left = edge[0]
  27.     right = edge[1]
  28.     if left is not None and right is not None:
  29.         if graph[left] is None and graph[right] is None:
  30.             graph[left] = i
  31.             graph[right] = i
  32.             i = i + 1
  33.         elif graph[left] is None and graph[right] is not None:
  34.             graph[left] = graph[right]
  35.         elif graph[left] is not None and graph[right] is None:
  36.             graph[right] = graph[left]
  37.  
  38.     else:
  39.         anyone = edge[0]
  40.         if graph[anyone] is None:
  41.             graph[anyone] = i
  42.  
  43. for edge in edges:
  44.     left = edge[0]
  45.     right = edge[1]
  46.     if (left is not None and right is not None) and (graph[left] != graph[right]) and left != right:
  47.         ind1 = graph[right]
  48.         for (k, v) in graph.items():
  49.             if v == ind1 :
  50.                 graph[k] = graph[left]
  51.  
  52.  
  53. for (k, v) in graph.items():
  54.             if v is None :
  55.                 i = i+1
  56.                 graph[k] = i
  57. print(graph)
  58.  
  59. res = defaultdict(list)
  60. for key, val in sorted(graph.items()):
  61.     res[val].append(key)
  62.  
  63.  
  64. print(len(res) - 1)
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement