M01258: Agri-Net
prim, http://cs101.openjudge.cn/dsapre/01258/
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course. Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms. Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm. The distance between any two farms will not exceed 100,000.
输入
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
输出
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
样例输入
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0样例输出
28来源
USACO 102
经典Prim算法
#王昊 光华管理学院
from heapq import heappop, heappush
while True:
try:
n = int(input())
except:
break
mat, cur = [], 0
for i in range(n):
mat.append(list(map(int, input().split())))
d, v, q, cnt = [100000 for i in range(n)], set(), [], 0
d[0] = 0
heappush(q, (d[0], 0))
while q:
x, y = heappop(q)
if y in v:
continue
v.add(y)
cnt += d[y]
for i in range(n):
if d[i] > mat[y][i]:
d[i] = mat[y][i]
heappush(q, (d[i], i))
print(cnt)"""
The problem described is a classic example of finding the Minimum Spanning Tree
(MST) in a weighted graph. In this scenario, each farm represents a node in
the graph, and the fiber required to connect each pair of farms represents
the weight of the edges between the nodes.
One of the most common algorithms to find the MST is Kruskal’s algorithm.
Alternatively, Prim’s algorithm could also be used. Below is a Python
implementation using Kruskal’s algorithm.
First, we need to parse the input, then apply the algorithm to find the MST,
and finally sum the weights of the chosen edges to output the result.
"""
class DisjointSetUnion:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
xr = self.find(x)
yr = self.find(y)
if xr == yr:
return False
elif self.rank[xr] < self.rank[yr]:
self.parent[xr] = yr
elif self.rank[xr] > self.rank[yr]:
self.parent[yr] = xr
else:
self.parent[yr] = xr
self.rank[xr] += 1
return True
def kruskal(n, edges):
dsu = DisjointSetUnion(n)
mst_weight = 0
for weight, u, v in sorted(edges):
if dsu.union(u, v):
mst_weight += weight
return mst_weight
def main():
while True:
try:
n = int(input().strip())
edges = []
for i in range(n):
# Since the input lines may continue onto others, we read them all at once
row = list(map(int, input().split()))
for j in range(i + 1, n):
if row[j] != 0: # No need to add edges with 0 weight
edges.append((row[j], i, j))
print(kruskal(n, edges))
except EOFError: # Exit the loop when all test cases are processed
break
if __name__ == "__main__":
main()from heapq import heappop, heappush, heapify
def prim(graph, start_node):
mst = set()
visited = set([start_node])
edges = [
(cost, start_node, to)
for to, cost in graph[start_node].items()
]
heapify(edges)
while edges:
cost, frm, to = heappop(edges)
if to not in visited:
visited.add(to)
mst.add((frm, to, cost))
for to_next, cost2 in graph[to].items():
if to_next not in visited:
heappush(edges, (cost2, to, to_next))
return mst
while True:
try:
N = int(input())
except EOFError:
break
graph = {i: {} for i in range(N)}
for i in range(N):
for j, cost in enumerate(map(int, input().split())):
graph[i][j] = cost
mst = prim(graph, 0)
total_cost = sum(cost for frm, to, cost in mst)
print(total_cost)思路:最小生成树,把边按照权重从小到大排序,每次用并查集判断一条边是否有必要添加
# 钟明衡 物理学院
p = []
def P(x):
if p[x] != x:
p[x] = P(p[x])
return p[x]
while True:
try:
n = int(input())
except EOFError:
break
ans = 0
M = [list(map(int, input().split())) for _ in range(n)]
p = [i for i in range(n)]
l = []
for i in range(n):
for j in range(n):
if i != j:
l.append((i, j, M[i][j]))
l.sort(key=lambda x: x[2])
for i, j, k in l:
pi, pj = P(i), P(j)
if pi != pj:
p[pi] = pj
ans += k
print(ans)