最小生成樹(prim)

假設V是圖中頂點的集合,E是圖中邊的集合,TE爲最小生成樹中的邊的集合,則prim算法通過以下步驟可以得到最小生成樹:

  1:初始化:U={u 0},TE={}。此步驟設立一個只有結點u 0的結點集U和一個空的邊集TE作爲最小生成樹的初始行態,在隨後的算法執行中,這個行態會不斷的發生變化,直到得到最小生成樹爲止。

  2:在所有u∈U,v∈V-U的邊(u,v)∈E中,找一條權最小的邊(u 0,v 0),將此邊加進集合TE中,並將此邊的非U中頂點加入U中。此步驟的功能是在邊集E中找一條邊,要求這條邊滿足以下條件:首先邊的兩個頂點要分別在頂點集合U和V-U中,其次邊的權要最小。找到這條邊以後,把這條邊放到邊集TE中,並把這條邊上不在U中的那個頂點加入到U中。這一步驟在算法中應執行多次,每執行一次,集合TE和U都將發生變化,分別增加一條邊和一個頂點,因此,TE和U是兩個動態的集合,這一點在理解算法時要密切注意。

  3:如果U=V,則算法結束;否則重複步驟2。可以把本步驟看成循環終止條件。我們可以算出當U=V時,步驟2共執行了n-1次(設n爲圖中頂點的數目),TE中也增加了n-1條邊,這n-1條邊就是需要求出的最小生成樹的邊。

 

O(∩_∩)O哈哈~發一個赤裸裸的求最小生成的題目(pku 1258)。以後比較複雜一點的最小生成樹我再慢慢做。雖然這個最小生成樹很簡單,但我一直沒有看,所以沒有明白,今天終於看懂了~~~~

 

Agri-Net
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 15966   Accepted: 6494

Description

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.

Input

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.

Output

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.

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章