Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import heapq

class DisjointSetUnion:
def __init__(self, n):
self.parents = list(range(n))
self.ranks = [0] * n

def find(self, x):
if self.parents[x] != x:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]

def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)

if root_x == root_y:
return

if self.ranks[root_x] > self.ranks[root_y]:
self.parents[root_y] = root_x
elif self.ranks[root_x] < self.ranks[root_y]:
self.parents[root_x] = root_y
else:
self.parents[root_y] = root_x
self.ranks[root_x] += 1

def kruskal_mst(graph):
n = len(graph)
mst_weight = 0
visited = [False] * n
edges = []

# Add edges to the priority queue
for i in range(n):
for neighbor, weight in graph[i]:
if i < neighbor:
heapq.heappush(edges, (weight, i, neighbor))

# Process edges in the priority queue
dsu = DisjointSetUnion(n)
while edges:
weight, u, v = heapq.heappop(edges)

if not visited[u] and not visited[v]:
visited[u] = visited[v] = True
mst_weight += weight
dsu.union(u, v)

return mst_weight

if __name__ == "__main__":
# Example graph
graph = [
[(1, 3), (2, 5)],
[(0, 3), (2, 1)],
[(0, 5), (1, 1)],
[],
[],
]

print("Minimum Spanning Tree weight:", kruskal_mst(graph))
55 changes: 55 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import heapq

class DisjointSetUnion:
def __init__(self, n):
self.parents = list(range(n))
self.ranks = [0] * n

def find(self, x):
if self.parents[x] != x:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]

def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)

if root_x == root_y:
return

if self.ranks[root_x] > self.ranks[root_y]:
self.parents[root_y] = root_x
elif self.ranks[root_x] < self.ranks[root_y]:
self.parents[root_x] = root_y
else:
self.parents[root_y] = root_x
self.ranks[root_x] += 1

def kruskal(n, edges):
dsu = DisjointSetUnion(n)
visited = [False] * n
edges.sort(key=lambda edge: edge[2])
mst_weight = 0

for edge in edges:
u, v, weight = edge
if not visited[u] and not visited[v]:
if dsu.find(u) != dsu.find(v):
dsu.union(u, v)
visited[u] = visited[v] = True
mst_weight += weight

return mst_weight

def read_graph(file_name):
n, m = map(int, input().split())
edges = []
for _ in range(m):
u, v, w = map(int, input().split())
edges.append((u - 1, v - 1, w))
return n, edges

if __name__ == "__main__":
file_name = "test.txt"
n, edges = read_graph(file_name)
print(kruskal(n, edges))