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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| import sys
inf = float("inf") vis, c = [False] * 25, [False] * 25 mst = [inf] * 25 s, ans, deg =0, 0, 0 conn = [0]*25 dic = {"Park":1} g, tree = [[inf]*25 for _ in range(25)], [[inf]*25 for _ in range(25)] ver, p = [0]*25, 0 f, fx, fy = [0]*25, [0]*25, [0]*25
n = int(sys.stdin.readline()) cnt = 1 for _ in range(n): a,b,z = sys.stdin.readline().split() if a != "Park" and a not in dic: cnt += 1 dic[a] = cnt if b != "Park" and b not in dic: cnt += 1 dic[b] = cnt g[dic[a]][dic[b]] = min(int(z), g[dic[a]][dic[b]]) g[dic[b]][dic[a]] = min(int(z), g[dic[b]][dic[a]]) s = int(sys.stdin.readline())
def prim(root): """对 ver中的 p个点求 mst""" global ans, p, deg mst[root] = 0 for i in range(1, p+1): x = 0 for j in range(1, p+1): if not vis[ver[j]] and (x == 0 or mst[ver[x]] > mst[ver[j]]): x = j vis[ver[x]] = True for j in range(1, p+1): y = ver[j] if not vis[y] and mst[y] > g[ver[x]][y]: mst[y], conn[y] = g[ver[x]][y], ver[x] closest = root for i in range(1, p+1): if ver[i] == root: continue x = ver[i] ans += mst[x] tree[conn[x]][x] = tree[x][conn[x]] = mst[x] if g[1][closest] > g[1][x]: closest = x deg += 1 ans += g[1][closest] tree[1][closest] = tree[closest][1] = g[1][closest]
def dfs(x): global p ver[p+1],p = x, p+1 c[x] = True for y in range(1, cnt+1): if g[x][y] != inf and not c[y]: dfs(y)
def prim_for_all_comp(): global p for i in range(2,25): vis[i], mst[i] = False, inf c[1] = True vis[1] = True for i in range(2,cnt+1): if not c[i]: p = 0 dfs(i) prim(i)
def dp(x): vis[x] = True for y in range(2, cnt + 1): if tree[x][y] != inf and not vis[y]: if f[x] > tree[x][y]: f[y] = f[x] fx[y],fy[y] = fx[x], fy[x] else: f[y] = tree[x][y] fx[y], fy[y] = x, y dp(y)
def solve(): """用于加边""" global ans min_val, mini = inf, 0 for i in range(2,cnt+1): if tree[1][i] != inf or g[1][i] == inf: continue if g[1][i] - tree[fx[i]][fy[i]] < min_val: min_val = g[1][i] - tree[fx[i]][fy[i]] mini = i if min_val >= 0: return False ans += min_val tree[fx[mini]][fy[mini]] = tree[fy[mini]][fx[mini]] = inf tree[1][mini] = tree[mini][1] = g[1][mini] f[mini] = g[1][mini] fx[mini], fy[mini] = 1, mini for i in range(2,25): vis[i] = False dp(mini) return True
"""主函数"""
prim_for_all_comp() for i in range(2,25): vis[i] = False dp(1) while deg < s: if not solve(): break deg += 1 print(f'Total miles driven: {ans}')
|