数据结构:最小生成树算法模板prim和kruskal(考研)

1.prim

#include 
#include 
#include 
using namespace std;

const int N=510;
const int INF=0x3f3f3f3f;
int dist[N];//保存距离
bool st[N];//标记点是否已经被访问过
int g[N][N];//邻接矩阵存储图

int n, m;

//返回值为最小生成树的权值
int prim() { 
	memset(dist, INF, sizeof(dist));
	int res = 0;
	for(int i=0; i

2.kruskal

#include 
#include 
using namespace std;

const int N=510;
const int M=1000;
const int INF=0x3f3f3f3f;

int father[N];

int find(int x) {
	int a = x;
	while(x != father[x]) x = father[x];
	while(a != father[a]) {
		int z = a;
		father[z] = x;
		a = father[a];
	}
	return x;
}

void Union(int a, int b) {
	int fa = find(a);
	int fb = find(b);
	if(fa != fb) father[fa] = fb;
}

//边类
struct Edge{
	int a, b;
	int weight;
}edges[M];


//返回值为MST的权值
int kruskal() {
	int res = 0;
	int cnt = 0;
	sort(edges, edges+m, [](const Edge &a, const Edge& b) {return a.weight < b.weight;});
	for(int i=1; i<=n; ++i) father[i] = i;//初始化并查集数组
	
	//遍历边集   已经按照权值由小到大排好序了
	for(int i=0; i

你可能感兴趣的:(数据结构,图论)