最小生成树问题有两种经典的算法,分别是Prim和Kruskal,他们的代码有很多种,但要使复杂度更低,算法的具体实现过程还是值得讨论的:
这里分别给出相对复杂度更低一点的代码:
Prim:
struct node{
int u,w;
node(){
};
node(int a, int b)
{
this->u = a;
this->w = b;
}//构造函数
bool operator<(const node& a)
const{
return this->w > a.w
}//比较运算函数用以建优先队列
}Edge[101];
struct node2{
int len;
int v[101];
int w[101];
}V[101];
上述步骤已经顺利写出了两组数据结构,第一组是储存待会构造优先队列的数据,第二组是储存我们输入的边、点集,接下来是主函数:
int main()
{
int N,i,a,b,c;
for(i = 0; i <= 100; i++)
V[i].len = 0;
scanf("%d",&N);
while(scanf("%d%d%d",&a,&b,&c)
{
V[a].v[len] = b;
V[a].w[len++] =