Advertisement
GreenMap

Лабораторная работа 4 МАПКС Алгоритм Краскала

Nov 19th, 2020
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. def find_value(l, value):
  2.     result = []
  3.     for i, val in enumerate(l):
  4.         if value == val:
  5.             result.append(i)
  6.     return result
  7. def is_cycle(edges):
  8.     ways = ["0"]
  9.     result = False
  10.     last_hop = None
  11.     while True:
  12.         print(ways)
  13.         for way in ways:
  14.             ways.remove(way)
  15.             for end_edge_index in find_value(edges[0], int(way[-1])):
  16.                 if not (str(edges[1][end_edge_index]) + way[-1]) in way:
  17.                     ways.append(way + str(edges[1][end_edge_index]))
  18.         for way in ways:
  19.             if way[-1] in way[0:-1]:
  20.                 result = True
  21.         if result:
  22.             break
  23.         if ways[:] == last_hop:
  24.             break
  25.         last_hop = ways[:]
  26.     return result
  27. m_size = int(input("Размер матрицы: "))
  28. matric = []
  29. for i in range(0, m_size):
  30.     converted_string = []
  31.     for num in input("Введите " + str(i + 1) + " срочку матрицы: ").split(" "):
  32.         converted_string.append(int(num))
  33.     matric.append(converted_string)
  34. edges = [[], []]
  35. for i_string in range(0, m_size):
  36.     for i_val in range(0, m_size):
  37.         if matric[i_string][i_val] == 1:
  38.             edges[0].append(i_string)
  39.             edges[1].append(i_val)
  40. weight = []
  41. for edge_index in range(0, len(edges[0])):
  42.     weight.append(int(input("Введите вес для ребра " + str(edges[0][edge_index] + 1) +
  43.                             "-" + str(edges[1][edge_index] + 1) + ":")))
  44. result = [[],[]]
  45. while not len(weight) == 0:
  46.     print(result)
  47.     choosen_edge_index = weight.index(min(weight))
  48.     result[0].append(edges[0][choosen_edge_index])
  49.     result[1].append(edges[1][choosen_edge_index])
  50.     weight.pop(choosen_edge_index)
  51.     edges[0].pop(choosen_edge_index)
  52.     edges[1].pop(choosen_edge_index)
  53.     if is_cycle(result):
  54.         result[0].pop()
  55.         result[1].pop()
  56. print(result)
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement