数据结构之并查集:并查集解决案例, Python——21
生活随笔
收集整理的這篇文章主要介紹了
数据结构之并查集:并查集解决案例, Python——21
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
并查集解決案例暢通工程
案例問題介紹:
- 某省調查城鎮交通狀況,得到現有城鎮道路統計表,表中列出了每條道路直接連通的城鎮。省政府"暢通工程”的目標是使全省任何兩個城鎮間都可以實現交通(但不一定有直接的道路相連,只要互相間接通過道路可達即可)。問最少還需要建設多少條道路?在我們的測試數據文件夾中有一個trffic project.txt文件,它就是誠征道路統計表,下面是對數據的解釋:
解題思路:
數據集
traffic.txt:
20 7 0 1 6 9 3 8 5 11 2 12 6 10 4 8Python功能實現及測試
from Structure.UF.UF_Tree_Weighted import UF_Tree_Weightedwith open('../traffic.txt', 'r') as f:total = int(f.readline())uft = UF_Tree_Weighted(total)connected_nums = int(f.readline())# print(connected_nums)for i in range(connected_nums):road = f.readline().split()uft.unite(int(road[0]), int(road[1]))# print(uft.in_the_same_group(int(road[0]), int(road[1])))print(uft.num_groups)print(uft.groups)print(f"Elements number in each group: {uft.nums_in_each_group}")print(f"To make the province's traffic fluent, "f"the number of remanent roads should be connected is {uft.count_groups()-1}")運行結果
13 [1, 1, 12, 8, 8, 11, 9, 7, 8, 9, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19] Elements number in each group: [0, 2, 0, 0, 0, 0, 0, 1, 3, 3, 0, 2, 2, 1, 1, 1, 1, 1, 1, 1] To make the province's traffic fluent, the number of remanent roads should be connected is 12只需要調用上一節實現的路徑壓縮優化后的并查集即可實現
總結
以上是生活随笔為你收集整理的数据结构之并查集:并查集解决案例, Python——21的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ub c语言,操作系统之LRU算法 C语
- 下一篇: 报错:OMP: Error #15: I