1.Prim算法
思路:
将顶点集V分为两部分S和V-S,S表示已经加入生成树的点集,算法的开始可以选取任意一个顶点加入S,之后每次在V-S中寻找到达S(即已构造的生成树)的距离最小的点,作为下一个顶点加入,直到所有顶点加入S后,或者不能再加入点时(图不连通)完毕
模板(邻接矩阵实现):
//prim函数返回最小生成树的边权值之和
//cost[][]为邻接矩阵,low[]为顶点到已加入到生成树中所有顶点的最小距离,n为顶点个数
int prim(int cost[][MAXN],int n)
{
int low[MAXN],vis[MAXN];
vis[0]=1; //加入一个顶点做为起始点
//初始的距离就是所有点到最初点的距离,不能到达为INF
for(int i = 1 ; i < n ; i++)
low[i] = cost[0][i];
int res=0; //权值和
for(int i = 1 ; i < n ; i++)
{
int minc = INF; //V-S中到达S的最小权值
int pos = -1;
for(int j = 0; j < n ; j++)
if(!vis[j] && low[j] < minc) //更新最小值并记录这个顶点
{
minc = low[j];
pos = j;
}
if(minc = INF) //找不到更近的点,原图不连通
return -1;
res+=minc;
vis[pos]=1; //将最小点加入S
for(int j = 0 ; j < n ; j++)
if(!vis[j] && low[j] > cost[pos][j]) //更新所有未加入的点到生成树的最小距离
low[j] = cost[pos][j];
}
return res;
}
2. Kruskal算法
思路: 每次选取没有参与构造最小生成树并且加入之后不会构成回路的边中权值最小的一条作为最小生成树的一条新边,直至选择了V-1条边,此时便构成了一棵最小生成树。为了判断一个边加入时是否会构成回路以决定是否选择该边,一般使用并查集来将所有已经互相连通的顶点加入到一个集合中,在决定是否将一条边作为最小生成树的新边时,只需要判断该边的两个顶点是否在同一集合中,如果是则舍去该边,否则将该边的两个点并至同一集合并将该边作为生成树的新边
模板:
#include "iostream"
#include "cstring"
#include "algorithm"
#include "cmath"
#include "cstdio"
#include "sstream"
#include "queue"
#include "vector"
#include "string"
#include "stack"
#include "cstdlib"
#include "deque"
#include "fstream"
#include "map"
using namespace std;
typedef long long LL;
const int INF = 0xfffffff;
struct edge
{
int s;
int e;
int weight;
bool operator < (const edge&b) const{
return weight < b.weight;
}
};
edge e[10000];
int set[100];
int find(int x)
{
return set[x] != x ? set[x] = find(set[x]) : x;
}
void merger(int x,int y)
{
((x=find(x)) != (y=find(y))) && set[x]=y;
}
int kru(int n,int m) //顶点数,边数
{
for(int i = 0 ; i < 100 ; i++)
set[i]=i;
sort(e,e+m);
int res=0; //权值
int cnt=0; //已构造的边数
for(int i = 0 ; i < m ; i++)
{
int u = find(e[i].e);
int v = find(e[i].s);
if(u != v) //无环,则加入
{
cnt++;
res+=e[i].weight;
merger(u,v);
}
if(cnt == n-1) //边数 = 顶点数-1
return res;
}
return -1;
}