遇到一道题,简单说就是找一个图的最小生成树,大概有两种常用的算法: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被任意选为起始点。顶点ABEF通过单条边与D相连。A是距离D最近的顶点,因此将A及对应边AD以高亮表示。 C, G A, B, E, F D

下一个顶点为距离DA最近的顶点。BD为9,距A为7,E为15,F为6。因此,FDA最近,因此将顶点F与相应边DF以高亮表示。 C, G B, E, F A, D
算法继续重复上面的步骤。距离A为7的顶点B被高亮表示。 C B, E, G A, D, F

在当前情况下,可以在CEG间进行选择。CB为8,EB为7,GF为11。E最近,因此将顶点E与相应边BE高亮表示。 C, E, G A, D, F, B

这里,可供选择的顶点只有CGCE为5,GE为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)的更多相关文章

  1. 最小生成树问题---Prim算法与Kruskal算法实现(MATLAB语言实现)

    2015-12-17晚,复习,甚是无聊,阅<复杂网络算法与应用>一书,得知最小生成树问题(Minimum spanning tree)问题.记之. 何为树:连通且不含圈的图称为树. 图T= ...

  2. 最小生成树问题---Prim算法学习

    一个具有n个节点的连通图的生成树是原图的最小连通子集,它包含了n个节点和n-1条边.若砍去任一条边,则生成树变为非连通图:若增加一条边,则在图中形成一条回路.本文所写的是一个带权的无向连通图中寻求各边 ...

  3. 最小路径(prim)算法

    #include <stdio.h>#include <stdlib.h>/* 最小路径算法 -->prim算法 */#define VNUM 9#define MV 6 ...

  4. 算法之prim算法

    最小生成树是数据结构中图的一种重要应用,它的要求是从一个带权无向完全图中选择n-1条边并使这个图仍然连通(也即得到了一棵生成树),同时还要考虑使树的权最小. prim算法就是一种最小生成树算法. 普里 ...

  5. 最小生成树问题:Kruskal算法 AND Prim算法

    Kruskal算法: void Kruskal ( ) {     MST = { } ;                           //边的集合,最初为空集     while( Edge ...

  6. 最小生成树问题(prim算法)POJ-1258 Agri-Net

    /* 这个题很水,但是,莫名其妙runtime error一晚上,重写了一遍就又没了,很伤心! 题意很简单,大致为n个村庄,连光缆,要求连上所有村庄的长度最短. 输入n,接着是n*n的矩阵,直接用pr ...

  7. 【算法】Kruskal算法(解决最小生成树问题) 含代码实现

    Kruskal算法和Prim算法一样,都是求最小生成树问题的流行算法. 算法思想: Kruskal算法按照边的权值的顺序从小到大查看一遍,如果不产生圈或者重边,就把当前这条边加入到生成树中. 算法的正 ...

  8. 最小生成二叉树-prim算法

    1.prim算法:一种计算生成最小生成树的方法,它的每一步都会为一棵生长中的树添加一条边. 2.时间复杂度:

  9. hdu 1102 Constructing Roads (Prim算法)

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1102 Constructing Roads Time Limit: 2000/1000 MS (Jav ...

随机推荐

  1. mysql学习(2)-Navicat Premium 12 链接MySQL8.0.11数据库报2059错误

    Navicat Premium 12 链接MySQL8.0.11数据库报2059错误 1,问题现象 安装完MySQL8.0.11和Navicat Premium12后,我们会用Navicat去测试连接 ...

  2. PAT甲题题解-1046. Shortest Distance (20)-做了一个假的最短路,水

    一开始以为是最短路,结果是给你一个环,让你求环上两点之间的距离...那还做毛线 然而还是得做毛线 #include <iostream> #include <cstdio> # ...

  3. C++ 多态Polymorphism 介绍+动态绑定、静态绑定

    什么是多态? 多态(polymorphism)一词最初来源于希腊语polumorphos,含义是一种物质的多种形态. 在专业术语中,多态是一种运行时绑定机制(run-time binding) ,通过 ...

  4. 20135202闫佳歆--week2 操作系统是如何工作的--学习笔记

    此为个人学习笔记存档 week 2 操作系统是怎么工作的 一.计算机是如何工作的?--三个法宝 (一)三个法宝 1.存储程序计算机 所有计算机的基础性的逻辑框架. 2.函数调用堆栈 在低级语言中并不很 ...

  5. WBS功能分解及甘特图

    产品 一级子功能 二级子功能 三级子功能 时间(小时)  食物链教学工具 属性面板 功能按键 选择环境 1       自定义生物 2       生物连线与删除 5       显示食物链 1   ...

  6. 小程序 JM

    // 本地 // 'https://ly.com/' // 短信验证码参数: let dataValue = { 'type': 1, mobile: '13615814562' }; dataVal ...

  7. powershell远程管理服务器磁盘空间的实现代码

    一.启用远程管理 1.将管理服务器的trusthost列表改为* 运行Set-item wsman:localhostclienttrustedhosts ?value * 2.在远程服务器上运行En ...

  8. 统计nginx日志的状态码

    日志格式 61.159.140.123 - - [23/Aug/2014:00:01:42 +0800] "GET /favicon.ico HTTP/1.1" 404 \ &qu ...

  9. linux下&、nohup与screen的比较

    & 首先,linux进程是区分前台进程和后台进程的. 通常,在终端输入的命令执行的前台进程模式.如果一个命令要执行好久,就会阻塞住终端好久,不能进行其他工作,所以,我们可以把执行花费时间很长的 ...

  10. Java微信二次开发(二)

    第二天,做微信文本消息接口请求与发送 需要导入库:dom4j-1.6.1.jar,xstream-1.3.1.jar 第一步:新建包com.wtz.message.response,新建类BaseMe ...