最小生成树的经典算法(Prim算法、kruskal算法)

来源:互联网 发布:2016真实挂机赚钱软件 编辑:程序博客网 时间:2024/06/03 12:27
最小生成树的经典算法
  • Prim算法
Prim算法用于求无向图的最小生成树。
   设图G =(V,E),其生成树的顶点集合为U。
   ①、把v0放入U。
   ②、在所有u∈U,v∈V-U的边(u,v)∈E中找一条最小权值的边,加入生成树。
   ③、把②找到的边的v加入U集合。如果U集合已有n个元素,则结束,否则继续执行②。
 
  • kruskal算法

 假设WN=(V,{E}) 是一个含有n 个顶点的连通网,则按照克鲁斯卡尔算法构造最小生成树的过程为:先构造一个只含n 个顶点,而边集为空的子图,若将该子图中各个顶点看成是各棵树上的根结点,则它是一个含有n 棵树的一个森林。之后,从网的边集E 中选取一条权值最小的边,若该条边的两个顶点分属不同的树,则将其加入子图,也就是说,将这两个顶点分别所在的两棵树合成一棵树;反之,若该条边的两个顶点已落在同一棵树上,则不可取,而应该取下一条权值最小的边再试之。依次类推,直至森林中只有一棵树,也即子图中含有n-1条边为止。




举一个具体实例:POJ 1251


Jungle Roads
Time Limit:1000MS Memory Limit:10000KTotal Submissions:13276 Accepted:5901

Description

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.
Input
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.
Output
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.
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

Source
Mid-Central USA 2002



问题描述:
Lagrishan的一个热带岛屿上的行政长官有一个问题要解决。他决定把几年前得到的外国援助资金用于修建村庄之间的道路。但是丛林比道路多太多了,使道路网络的维护太过于昂贵了。理事会必须选择停止维修一些道路。上述左侧图显示当前所有使用中的道路,以及现在每月的维护费用。当然,村庄之间必需有一些公路能够相通,即使路线并不像以前一样短。行政长官想告诉理事会怎样才使每月的花费最小,并且所维持的道路,将连接所有村庄。上面的地图标记了村庄A到I。图显示了每月能够维护道路的最小费用为216aacms。你的任务是编写一个程序,将解决这些问题。
输入:
输入包含的数据集个数在100以内,以0作为最后一行。每个数据集的第一行只包含一个表示村庄个数的数n,1<n<27,并且这n个村庄是由大写字母表里的前n个字母表示。接下来的n- 1行是由字母表的前n-1个字母开头。最后一个村庄表示的字母不用输入。对于每一行,以每个村庄表示的字母开头,然后后面跟着一个数字,表示有多少条道路可以从这个村到后面字母表中的村庄。如果k是大于0,表示该行后面会表示k条道路的k个数据。每条道路的数据是由表示连接到另一端村庄的字母和每月维修该道路的花费组成。维修费用是正整数的并且小于100。该行的所有数据字段分隔单一空白。该公路网将始终连接所有的村庄。该公路网将永远不会超过75条道路。没有任何一个村庄会有超过15条的道路连接到其他村庄(之前或之后的字母)。在下面的示例输入,其中第一个数据集是与上面的地图相一致的。
输出:
输出是每行一个整数,表示每个数据集中每月维持道路系统连接到所有村庄所花费的最低成本。Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit. 注意:这是一种强力的解决方案,不是每一个数据集的所生成的道路网都能在规定的1分钟之内的时间完成。




感想:这个题比较纠结、、、可能是poj的测试数据有问题。getchar()应该也可以取空格吧。但是用getchar()就是不对。。。致使我提交了很多遍。出现了很多次RE。本以为只能用c++输入了、最终还是发现了一个用c输入的方法。就是把getchar()用空格表示,并且放在scanf()中、竟然奇迹的AC了。

小技巧:对于最小生成树,有两种算法可以解决。一种是Prim算法,该算法的时间复杂度为O(n2),与图中边数无关,该算法适合于稠密图,而另外一种是Kruskal,该算法的时间主要取决于边数,它较适合于稀疏图。



具体代码如下:


Prim算法:

#include <stdio.h>#include<string.h>#define N 28 #define INF 32768int g[N][N],n;void prim(){     int min,sum=0;    int i,j,k;int low[N];    for(i=0;i<n;i++)    {        low[i]=g[0][i];    }    low[0]=-1;    for(i=1;i<n;i++)    {        min=INF;        for(j=0;j<n;j++)            if(low[j]>0&&low[j]<min)            {                min=low[j];                k=j;            }            low[k]=-1;            for(j=0;j<n;j++)                if(g[k][j]>0&&g[k][j]<low[j])                {                    low[j]=g[k][j];                }            if(min!=INF)sum+=min;    }    printf("%d\n", sum);}int main(){int i,m,x,a,b,j; char c1,c2;while(scanf("%d",&n)&&n){  for(i=0; i<=n; i++)            for(j=0; j<=n; j++)                g[i][j] =32768;for(i=0;i<n-1;i++){scanf(" %c %d",&c1,&m);a=c1-'A';while(m--){scanf(" %c %d",&c2,&x);b=c2-'A';g[b][a]=g[a][b]=x;}}prim();}return 0;}

kruskal算法

#include<stdio.h>
#include<stdlib.h>
struct f
{
int x,y;
int w;
}e[100];
int rank[30];
int father[30];
int cmp(const void *a, const void *b)
{
return (*(struct f *)a).w – (*(struct f *)b).w;
}
void Make_Set(int x)
{
father[x]=x;
rank[x]=0;
}
int Find_Set(int x)
{
if (x!=father[x])
{
father[x]=Find_Set(father[x]);
}
return father[x];
}
void Union(int x, int y)
{
if(rank[x]>rank[y])
{
father[y]=x;
}
else
{
if(rank[x]==rank[y])
nk[y]++;
father[x]=y;
}
}
int main()
{
int i,j,k,m,n,sum,x,y;
char c1,c2;
while(scanf("%d",&m)&&m)
{
k=0;
for(i=0;i<m;i++)
Make_Set(i);
for(i=0;i<m-1;i++)
{
scanf(" %c %d",&c1,&n);
for(j=0;j<n;j++)
{
scanf(" %c %d",&c2,&e[k].w);
e[k].x=c1-'A';
e[k].y=c2-'A';
k++;
}
}
qsort(e,k,sizeof(struct f),cmp);
sum=0;
for(i=0;i<k;i++)
{
x=Find_Set(e[i].x);
y=Find_Set(e[i].y);
if(x!=y)
{
Union(x,y);
sum+=e[i].w;
}
}
printf("%d\n",sum);
}
return 0;
}