遇到一道题,简单说就是找一个图的最小生成树,大概有两种常用的算法:Prim算法和Kruskal算法。这里先介绍Prim。随后贴出1924的算法实现代码。
Prim算法
1.概览
普里姆算法(Prim算法),图论中的一种算法,可在加权连通图里搜索最小生成树。意即由此算法搜索到的边子集所构成的树中,不但包括了连通图里的所有顶点(英语:Vertex (graph theory)),且其所有边的权值之和亦为最小。该算法于1930年由捷克数学家沃伊捷赫·亚尔尼克(英语:Vojtěch Jarník)发现;并在1957年由美国计算机科学家罗伯特·普里姆(英语:Robert C. Prim)独立发现;1959年,艾兹格·迪科斯彻再次发现了该算法。因此,在某些场合,普里姆算法又被称为DJP算法、亚尔尼克算法或普里姆-亚尔尼克算法。
2.算法简单描述
1).输入:一个加权连通图,其中顶点集合为V,边集合为E;
2).初始化:Vnew = {x},其中x为集合V中的任一节点(起始点),Enew = {},为空;
3).重复下列操作,直到Vnew = V:
a.在集合E中选取权值最小的边<u, v>,其中u为集合Vnew中的元素,而v不在Vnew集合当中,并且v∈V(如果存在有多条满足前述条件即具有相同权值的边,则可任意选取其中之一);
b.将v加入集合Vnew中,将<u, v>边加入集合Enew中;
4).输出:使用集合Vnew和Enew来描述所得到的最小生成树。
下面对算法的图例描述
下面对算法的图例描述
图例 | 说明 | 不可选 | 可选 | 已选(Vnew) |
---|---|---|---|---|
此为原始的加权连通图。每条边一侧的数字代表其权值。 | - | - | - | |
顶点D被任意选为起始点。顶点A、B、E和F通过单条边与D相连。A是距离D最近的顶点,因此将A及对应边AD以高亮表示。 | C, G | A, B, E, F | D | |
下一个顶点为距离D或A最近的顶点。B距D为9,距A为7,E为15,F为6。因此,F距D或A最近,因此将顶点F与相应边DF以高亮表示。 | C, G | B, E, F | A, D | |
算法继续重复上面的步骤。距离A为7的顶点B被高亮表示。 | C | B, E, G | A, D, F | |
在当前情况下,可以在C、E与G间进行选择。C距B为8,E距B为7,G距F为11。E最近,因此将顶点E与相应边BE高亮表示。 | 无 | C, E, G | A, D, F, B | |
这里,可供选择的顶点只有C和G。C距E为5,G距E为9,故选取C,并与边EC一同高亮表示。 | 无 | C, G | A, D, F, B, E | |
顶点G是唯一剩下的顶点,它距F为11,距E为9,E最近,故高亮表示G及相应边EG。 | 无 | G | A, D, F, B, E, C | |
现在,所有顶点均已被选取,图中绿色部分即为连通图的最小生成树。在此例中,最小生成树的权值之和为39。 | 无 | 无 | A, D, F, B, E, C, G |
在代码中实现的思路是:
1.任选一点,加入集合find
2.找到与find集合所邻接的所有边中最短的一个,并将该边所连接的另一个点加入到集合find中。
3.重复上述步骤,直到图中所有的点都被加入到find中。
题目和代码:
The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.
The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above.
The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages.
Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit.
/*
* 1924_Jungle Roads.cpp
* //最小生成树问题
* Created on: 2018年11月14日
* Author: Jeason
*/
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <sstream>
#include <queue>
#define N 30
using namespace std;
struct node {
int num;
int length;
};
vector <node> Tree[N];
vector <node> minTree[N];
vector <int> haveFind;
int num_point;
int visited[N];
int Min[][N*N*]; void init()
{
for( int i = ; i < num_point; i++ )
Tree[i].clear();
for( int i = ; i < num_point; i++ )
minTree[i].clear();
haveFind.clear();
memset(visited,,sizeof(visited));
memset(Min,,sizeof(Min));
} void readData()
{
char start;
int num_out;
cin >> start >> num_out;
while(num_out--){
char end;
int length;
cin >> end >> length;
node P1,P2;
P1.num = end - 'A';
P1.length = length;
P2.num = start - 'A';
P2.length = length;
Tree[ start - 'A'].push_back( P1 );
Tree[ end - 'A'].push_back( P2 );
}
} int findMin()
{
int m = ;
for( int i = ; i < N; i++ )
if( Min[][i] < Min[][m])
m = i;
return m;
} int main()
{
cin >> num_point;
while(num_point != ){
init();
int T = num_point - ;
while( T-- ){
readData(); //利用树的结构储存无向图
}
int root;
for(int i = ;i < num_point;i++){
for(int j = ; j < Tree[i].size();j++){
root = Tree[i][j].num ;
}
}
haveFind.push_back(root); //首先把A点加入
visited[root] = ;
while( haveFind.size() != num_point ){
memset(Min,,sizeof(Min));
for(int i = ;i < ;i++){
for(int j = ;j < N ;j++){
Min[i][j] = ;
}
}
int s = ;
for(int i = ; i < haveFind.size();i++ ){ //对已找到的所有点进行遍历
for(int j = ; j < Tree[haveFind[i]].size(); j++ ){ //遍历 所有已找到的点 所相互连接的点
if( visited[ Tree[haveFind[i]] [j].num ] == ){ //如果此相连的点没有访问过
Min[][ s ] = Tree[haveFind[i]][j].length;
Min[][ s ] = Tree[haveFind[i]][j].num; //子节点
Min[][s++] = haveFind[i]; //父亲节点
}
}
} int local = findMin(); haveFind.push_back( Min[][local] );
visited[ Min[][local] ] = ; node P1,P2;
P1.num = Min[][local];
P1.length = Min[][local];
P2.num = Min[][local];
P2.length = Min[][local];
minTree[ Min[][local] ].push_back( P1 );
minTree[ Min[][local] ].push_back( P2 );
} int ans = ;
for(int i = ;i < num_point;i++){
for(int j = ; j < minTree[i].size();j++){
ans += minTree[i][j].length;
}
}
cout << ans / << endl; cin >> num_point;
}
} /*
Sample Input 9
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0
Sample Output 216
30
*/