之前学了用普里姆算法来求最小生成树的权值和,但是它的时间复杂度为O(|V2|),使用优先级队列优化后,可以优化为O(|E|log|V|)。
克鲁斯卡尔算法可以在O(|E|log|E|)的时间复杂度内,求出最小生成树
克鲁斯卡尔算法的核心就是对边进行升序排序,然后从权值最小的边开始,加入最小生成树中,然后利用并查集,把最小生成树中的节点归为同一个集合。一条边只有当它的两个端点不在同一个集合中的时候,才能把它加入最小生成树中。
题目:GRL_2_A
AC代码:
#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include<cstdio>
using namespace std;
#define MAXV 10005
#define MAXE 100005
struct edge
{
int from, to, weight;
} eg[4*MAXE];
int v, e;
int head[MAXV] = {0};
int js_edges = 0;
int fa[MAXV] = {0};//并查集
int Rank[MAXV] = {0};
bool cmp(const edge &a,const edge &b)
{
return a.weight<b.weight;
}
void add_edges(int s,int t,int w)
{
eg[js_edges].from = s;
eg[js_edges].to =t;
eg[js_edges].weight = w;
js_edges++;
}
int find_set(int i)
{

最低0.47元/天 解锁文章
961

被折叠的 条评论
为什么被折叠?



