m0_62390985 2022-03-30 14:43 采纳率: 100%
浏览 379
已结题

如何插入txt, txt文件里面有matrix, 如何在python用minimum spanning tree 的算法来运行matrix, 并得出结果

如何插入任意一个txt文件,txt文件里面有一个matrix,matrix可以是任意的, 例如, 55, 66.
如何用minimum spanning tree 的kruskal算法来算出结果

我的想法 要用到adj
= numpy.loadtxt("graph.txt", delimiter=',')
这个公式来插入txt

要用kruskal的方法计算minimum spanning tree, 但是那个matrix(或者说edge, wight)不是直接输在python code里面, 而是通过插入一个txt格式的文件,txt文件里面有matrix,例如:
0,30,26,50,40
30,0,24,40,50
26,24,0,24,26
50,40,24,0,30
40,50,26,30,0
这是55格式的
也有可能是66格式, 不同数字。
要求无论插入的txt文本里面有什么样的matrix,python code都可以运行

我希望最后的output像这样
Following are the edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree: 19
可以参考 这个链接 https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/

并且希望output的顶点不是从0开始计, 而是从1开始
像‘(0,2)’ 变成 “(1,3)”

求解完整的算法

  • 写回答

8条回答 默认 最新

  • 这次真没糖 2022-03-30 22:49
    关注

    已完成,需要在代码的文件夹下新建一个graph.txt,
    内容如下

    img

    
    # Python program for Kruskal's algorithm to find
    # Minimum Spanning Tree of a given connected,
    # undirected and weighted graph
    
    
    # Class to represent a graph
    
    
    class Graph:
    
        def __init__(self, vertices):
            self.V = vertices  # No. of vertices
            self.graph = []  # default dictionary
            # to store graph
    
        # function to add an edge to graph
        def addEdge(self, u, v, w):
            self.graph.append([u, v, w])
    
        # A utility function to find set of an element i
        # (uses path compression technique)
        def find(self, parent, i):
            if parent[i] == i:
                return i
            return self.find(parent, parent[i])
    
        # A function that does union of two sets of x and y
        # (uses union by rank)
        def union(self, parent, rank, x, y):
            xroot = self.find(parent, x)
            yroot = self.find(parent, y)
    
            # Attach smaller rank tree under root of
            # high rank tree (Union by Rank)
            if rank[xroot] < rank[yroot]:
                parent[xroot] = yroot
            elif rank[xroot] > rank[yroot]:
                parent[yroot] = xroot
    
            # If ranks are same, then make one as root
            # and increment its rank by one
            else:
                parent[yroot] = xroot
                rank[xroot] += 1
    
        # The main function to construct MST using Kruskal's
            # algorithm
        def KruskalMST(self):
    
            result = []  # This will store the resultant MST
    
            # An index variable, used for sorted edges
            i = 0
    
            # An index variable, used for result[]
            e = 0
    
            # Step 1: Sort all the edges in
            # non-decreasing order of their
            # weight. If we are not allowed to change the
            # given graph, we can create a copy of graph
            self.graph = sorted(self.graph,
                                key=lambda item: item[2])
    
            parent = []
            rank = []
    
            # Create V subsets with single elements
            for node in range(self.V):
                parent.append(node)
                rank.append(0)
    
            # Number of edges to be taken is equal to V-1
            while e < self.V - 1:
    
                # Step 2: Pick the smallest edge and increment
                # the index for next iteration
                u, v, w = self.graph[i]
                i = i + 1
                x = self.find(parent, u)
                y = self.find(parent, v)
    
                # If including this edge does't
                # cause cycle, include it in result
                # and increment the indexof result
                # for next edge
                if x != y:
                    e = e + 1
                    result.append([u, v, w])
                    self.union(parent, rank, x, y)
                # Else discard the edge
    
            minimumCost = 0
            print("Edges in the constructed MST")
            for u, v, weight in result:
                minimumCost += weight
                print("%d -- %d == %d" % (u+1, v+1, weight))
            print("Minimum Spanning Tree", minimumCost)
    
    
    # Driver code
    data = []
    with open('graph.txt', mode='r', encoding='utf-8') as fp:
        data = fp.readlines()
        for i, item in enumerate(data):
            data[i] = item.split(',')
    
    n = len(data)
    g = Graph(n)
    for i in range(n):
        for j in range(n):
            g.addEdge(i, j, int(data[i][j]))
    
    # Function call
    g.KruskalMST()
    
    # This code is contributed by Neelam Yadav
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(7条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月31日
  • 已采纳回答 3月31日
  • 赞助了问题酬金100元 3月30日
  • 修改了问题 3月30日
  • 展开全部

悬赏问题

  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备