Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.73 KB | None | 0 0
  1. from problem import Problem
  2. import random
  3.  
  4. solutie = ''
  5. sol = ''
  6.  
  7. # A utility function to find set of an element i
  8. # (uses path compression technique)
  9. def find( parinte, i):
  10.     if parinte[i] == i:
  11.         return i
  12.     return find(parinte, parinte[i])
  13.  
  14. # A function that does union of two sets of x and y
  15. # (uses union by rank)
  16. def union( parinte, rank, x, y):
  17.     xroot = find(parinte, x)
  18.     yroot = find(parinte, y)
  19.  
  20.     # Attach smaller rank tree under root of
  21.     # high rank tree (Union by Rank)
  22.     if rank[xroot] < rank[yroot]:
  23.         parinte[xroot] = yroot
  24.     elif rank[xroot] > rank[yroot]:
  25.         parinte[yroot] = xroot
  26.  
  27.     # If ranks are same, then make one as root
  28.     # and increment its rank by one
  29.     else:
  30.         parinte[yroot] = xroot
  31.         rank[xroot] += 1
  32.  
  33.  
  34. # The main function to construct MST using Kruskal's
  35. # algorithm
  36. def KruskalMST(graph,V):
  37.     global solutie
  38.  
  39.     result =[] #This will store the resultant MST
  40.  
  41.     i = 0  # An index variable, used for sorted edges
  42.     e = 0  # An index variable, used for result[]
  43.  
  44.     # Step 1:  Sort all the edges in non-decreasing
  45.     # order of their
  46.     # weight.  If we are not allowed to change the
  47.     # given graph, we can create a copy of graph
  48.     graph = sorted(graph, key=lambda item: item[2])
  49.  
  50.     parent = []
  51.     rank = []
  52.  
  53.     # Create V subsets with single elements
  54.     for node in range(V):
  55.         parent.append(node)
  56.         rank.append(0)
  57.  
  58.     # Number of edges to be taken is equal to V-1
  59.     while e < V - 1:
  60.  
  61.         # Step 2: Pick the smallest edge and increment
  62.         # the index for next iteration
  63.         u, v, w = graph[i]
  64.         i = i + 1
  65.         x = find(parent, u)
  66.         y = find(parent, v)
  67.  
  68.         # If including this edge does't cause cycle,
  69.         # include it in result and increment the index
  70.         # of result for next edge
  71.         if x != y:
  72.             e = e + 1
  73.             result.append([u, v, w])
  74.             union(parent, rank, x, y)
  75.         # Else discard the edge
  76.  
  77.     # print the contents of result[] to display the built MST
  78.     solutie += "Muchiile arborelui de cost minim obtinut sunt urmatoarele:\n"
  79.  
  80.     for u, v, weight in result:
  81.         solutie += str(u) + " -- " + str(v) + " == " + str(weight) + '\n'
  82.  
  83.  
  84. class Problem42(Problem):
  85.  
  86.     def __init__(self):
  87.         statement = "Primind urmatorul graf, construiti arborele partial de cost minim (Kruskal):\n\n"
  88.         data = []
  89.  
  90.         V = random.randint(6, 9)  # Generez un numar de varfuri intre 6 si 9
  91.  
  92.         graph = []   # Dictionarul in care stocam graful
  93.  
  94.         matrice = [[0 for x in range(V)] for y in range(V)]  # Declar matricea de adiacenta si o initializez cu 0
  95.         for i in range(0, V):
  96.             for j in range(i + 1, V):   # Pentru fiecare element de deasupra diagonalei principale
  97.                 matrice[i][j] = random.randint(0, 1)    # generez 0 sau 1:  1 - exista muchie intre i si j;  0 - nu exista muchie
  98.                 matrice[j][i] = matrice[i][j]           # si fac matricea simetrica
  99.  
  100.         for i in range(0, V):
  101.             ok = 0
  102.             for j in range(0, V):
  103.                 if matrice[i][j] == 1:
  104.                     ok = ok + 1       # Numar cati de 1 sunt pe o linie;
  105.             if ok <= 1:               # daca e cel mult un 1
  106.                 for j in range(0, V):
  107.                     matrice[i][j] = 1       # populez toata linia cu 0
  108.                     matrice[j][i] = 1
  109.  
  110.         for i in range(0, V):
  111.             matrice[i][i] = 0       # Fac elementele de pe diagonala principala 0
  112.         statement += "Lista de muchii:\n"
  113.         for i in range(0, V):
  114.             for j in range(i + 1, V):       # Parcurg matricea deasupra diagonalei principale
  115.                 if matrice[i][j] == 1:      # daca elementul de pe pozitia [i][j] este 1
  116.                     c = random.randint(1, 30)       # generez un cost intre 1 si 20
  117.  
  118.                     statement += str(i) + '  ' + str(j) + ' -> ' + str(c) + '\n'
  119.                     graph.append([i, j, c])     # si adaug muchia si costul ei in graf
  120.  
  121.         KruskalMST(graph, V)
  122.  
  123.         super().__init__(statement, data)
  124.  
  125.  
  126.     def solve(self):
  127.  
  128.         solution = "Idee de rezolvare: \n"
  129.         solution += "Pas 1: Sortam muchiile crescator in functie de cost;\n"
  130.         solution += "pas 2: Alegem cea mai mica muchie. Verificam daca inchide un ciclu cu arborele\n"
  131.         solution += "format pana acum. Daca nu inchide un ciclu, includem muchia in arborele de cost minim;\n"
  132.         solution += "Pas 3: Repetam pasul 2 pana cand numarul muchiilor din arbore este cu unu mai putin decat numarul de noduri.\n\n"
  133.  
  134.         solution += solutie
  135.         return solution
  136.  
  137. p = Problem42()
  138. print(p.statement)
  139. print(p.solve())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement