最小生成树问题------------Prim算法(TjuOj_1924_Jungle Roads)
遇到一道题,简单说就是找一个图的最小生成树,大概有两种常用的算法: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
*/
最小生成树问题------------Prim算法(TjuOj_1924_Jungle Roads)的更多相关文章
- 最小生成树问题---Prim算法与Kruskal算法实现(MATLAB语言实现)
2015-12-17晚,复习,甚是无聊,阅<复杂网络算法与应用>一书,得知最小生成树问题(Minimum spanning tree)问题.记之. 何为树:连通且不含圈的图称为树. 图T= ...
- 最小生成树问题---Prim算法学习
一个具有n个节点的连通图的生成树是原图的最小连通子集,它包含了n个节点和n-1条边.若砍去任一条边,则生成树变为非连通图:若增加一条边,则在图中形成一条回路.本文所写的是一个带权的无向连通图中寻求各边 ...
- 最小路径(prim)算法
#include <stdio.h>#include <stdlib.h>/* 最小路径算法 -->prim算法 */#define VNUM 9#define MV 6 ...
- 算法之prim算法
最小生成树是数据结构中图的一种重要应用,它的要求是从一个带权无向完全图中选择n-1条边并使这个图仍然连通(也即得到了一棵生成树),同时还要考虑使树的权最小. prim算法就是一种最小生成树算法. 普里 ...
- 最小生成树问题:Kruskal算法 AND Prim算法
Kruskal算法: void Kruskal ( ) { MST = { } ; //边的集合,最初为空集 while( Edge ...
- 最小生成树问题(prim算法)POJ-1258 Agri-Net
/* 这个题很水,但是,莫名其妙runtime error一晚上,重写了一遍就又没了,很伤心! 题意很简单,大致为n个村庄,连光缆,要求连上所有村庄的长度最短. 输入n,接着是n*n的矩阵,直接用pr ...
- 【算法】Kruskal算法(解决最小生成树问题) 含代码实现
Kruskal算法和Prim算法一样,都是求最小生成树问题的流行算法. 算法思想: Kruskal算法按照边的权值的顺序从小到大查看一遍,如果不产生圈或者重边,就把当前这条边加入到生成树中. 算法的正 ...
- 最小生成二叉树-prim算法
1.prim算法:一种计算生成最小生成树的方法,它的每一步都会为一棵生长中的树添加一条边. 2.时间复杂度:
- hdu 1102 Constructing Roads (Prim算法)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1102 Constructing Roads Time Limit: 2000/1000 MS (Jav ...
随机推荐
- OAuth 2.0 Salesforce & Azure
最近在学习Salesforce,浅谈一下 OAuth 2.0 在Salesforce and Azure 之间的应用. 假设有这样一个场景,在Salesforce中需要用到Azure中的一些服务,那么 ...
- docker 安装 kali
1.安装 docker pull kalilinux/kali-linux-docker 2.运行容器 docker run -t -i kalilinux/kali-linux-docker /bi ...
- NumCPU()在slice中的使用
package main import ( "fmt" "runtime" ) var slice []int func main() { array := m ...
- (第十二周)Debug阶段成员贡献分
项目名:食物链教学工具 组名:奋斗吧兄弟 组长:黄兴 组员:李俞寰.杜桥.栾骄阳.王东涵 个人贡献分=基础分+表现分 基础分=5*5*0.5/5=2.5 成员得分如下: 成员 基础分 表现分 个人贡献 ...
- 用户场景模拟+Spec
场景模拟: Spec: 浏览包车信息-->登录-->选择包车城市-->选择去/回程-->选择路线-->预定-->选择包车日期-->出发时间和地点--> ...
- Linux命令(二十三) 磁盘管理命令(一) df,du,tune2fs
一. 查看磁盘占用空间情况 df df 命令用于查看硬盘空间的使用情况,还可以查看硬盘分区的类型或 inode 节点的使用情况等. df 命令常用参数如下: -a 显示所有文件系统的磁盘使用情况,包括 ...
- 六大Web负载均衡原理与实现
还有个姊妹篇也可以参考这个文章:LVS(Linus Virtual Server):三种负载均衡方式比较+另三种负载均衡方式, LVS 实现了负载均衡,NAT,DR,TUN zookeeper使用ZA ...
- [代码]--IIS发布网站浏览之后看到的是文件目录 & Internal Server Error 处理程序“ExtensionlessUrlHandler-ISAPI-4.0_64bit”在其模块列表中有一个错误模块“IsapiModule” 解决方法 & App_global.asax.pduxejp_.dll”--“拒绝访问。 ”
Q:IIS发布网站浏览之后看到的是文件目录 A:它出现了一个说到.NET4.0 更高框架什么的错误,所以我将 .NTE CRL版本由4.0改为2.0了,改为2.0后就出现了只能浏览文件目录了.改为4. ...
- 【题解】 bzoj1875: [SDOI2009]HH去散步 (动态规划+矩阵乘法)
bzoj1875,懒得复制,戳我戳我 Solution: 看到这道题,看的出是个dp,每个点\(t\)时刻到达的方案数等于\(t-1\)到连过来的点方案数之和 但又因为题目有要求不能走一样的边回去不是 ...
- 洛谷 P1344 [USACO4.4]追查坏牛奶Pollutant Control 解题报告
P1344 [USACO4.4]追查坏牛奶Pollutant Control 题目描述 你第一天接手三鹿牛奶公司就发生了一件倒霉的事情:公司不小心发送了一批有三聚氰胺的牛奶.很不幸,你发现这件事的时候 ...







