-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjurassicjigsaw.py
58 lines (51 loc) · 1.52 KB
/
jurassicjigsaw.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from heapq import heappop, heappush
from sys import stdin
class Graph:
def __init__(self, n, adj):
self.n = n
self.adj = adj
def mst(self):
return self._prims()
def _prims(self):
best = [0] * self.n
remaining = set(range(1,self.n))
visited = [True] + [False] * (self.n-1)
heap = []
edges = []
dist = 0
for i in range(1,self.n):
heappush(heap, (self.adj[0][i], 0, i))
best[i] = self.adj[0][i]
while len(edges) < self.n-1:
while True:
w, u, v = heappop(heap)
if visited[v]:
continue
break
edges.append((u,v))
dist += w
visited[v] = True
remaining.remove(v)
for x in remaining:
if self.adj[v][x] < best[x]:
best[x] = self.adj[v][x]
heappush(heap, (self.adj[v][x], v, x))
return dist, edges
def diff(str1,str2):
return sum(a != b for a,b in zip(str1,str2))
def construct_adj(n):
words = [None]*n
adj = [[0]*n for _ in range(n)]
for i in range(n):
words[i] = input()
for j in range(i):
adj[j][i] = diff(words[j], words[i])
adj[i][j] = adj[j][i]
return adj
n,_ = map(int,stdin.readline().split())
adj = construct_adj(n)
g = Graph(n,adj)
mst_len, mst = g.mst()
print(mst_len)
for edge in mst:
print(*edge)