数据:
图片:
分析:
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
const int MAXNUM = 1000 + 10; //顶点的最大值
const int INF= 0x3f3f3f3f; //边的最大值
int sumweight=0;
int n,m;
int edges[MAXNUM][MAXNUM]={0};
int lowcost[MAXNUM];
int near[MAXNUM];
string sh[7]={"","北京","天津","石家庄","呼和浩特","太原","济南"};
void Prim()
{
for(int i = 1;i <= n;i++)
{
lowcost[i] = edges[1][i];
near[i] = 1;
}
near[1]=-1;
for(int i = 1;i < n; i++)
{
int Min=INF;
int v=-1;
//在lowcost数组里中找未被访问的最最小值
for(int j=1;j<=n;j++)
{
if(near[j] != -1 && lowcost[j] < Min) //找最小lowcost
{
Min = lowcost[j];
v = j;
}
}
if(v != -1)
{
near[v]=-1; //表示v节点已经在生成树中
sumweight+=lowcost[v]; //最小代价
cout<<"---->"<<sh[v]<<"("<<lowcost[v]<<")";
for(int j = 1;j <= n;j++) //更新lowcost
{
if(near[j] != -1 && edges[v][j] < lowcost[j])
{
lowcost[j] = edges[v][j];
near[j] = v;
}
}
}
}
// printf("%d\n",sumweight);
}
int main()
{
int u, v, w;
cin>>n>>m; //n点 m条路
for(int i = 1;i <= m; i++)
{
scanf("%d %d %d",&u,&v,&w);
edges[u][v] = edges[v][u] = w;
}
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
{
if(i!=j&&edges[i][j] == 0)
edges[i][j] = INF;
}
cout<<"prim最小生成树顺序:北京(0)";
Prim();
cout<<endl<<"最小代价:"<< sumweight<<endl;
return 0;
}
输入数据:
6 15
2 1 103
3 1 270
3 2 267
4 1 408
4 2 495
4 3 385
5 1 406
5 2 426
5 3 168
5 4 335
6 1 366
6 2 280
6 3 273
6 4 648
6 5 416
结果: