开个100X100的数组,开始全置0,涂了就置1,最后统计1的个数
#include<iostream>
#include<string.h>
using namespace std;
const int inf = 0x3f3f3f3f;
int dist[1005][1005] = { 0 }, N = 0,M=0;
int prim()
{
int s = 1; //源点(最初的源点为1)
int m = 1; //记录最小生成树的顶点数
bool u[1005]; //记录某顶点是否属于最小生成树
int w = 0; //最小生成树的总权值
int minlength = 0; //每个新源点到其它点后的最短路和
int flag_point;
int low_dis[1005]; //各个源点s到其它点的最短路
memset(low_dis, inf, sizeof(low_dis));
memset(u, false, sizeof(u));
u[s] = true;
while (1)
{
if (m == N) //当最小生成树的顶点数等于原图的顶点数时,说明最小生成树查找完毕
break;
w = inf;
for (int j = 2; j <= N; j++)
{
if (!u[j] && low_dis[j]>dist[s][j]&&dist[s][j])
low_dis[j] = dist[s][j];
if (!u[j] && w>low_dis[j]&&low_dis[j])
{
w = low_dis[j];
flag_point = j; //记录最小权边中不属于最小生成树的点j
}
}
s = flag_point; //顶点j与旧源点合并
u[s] = true; //j点并入最小生成树(相当于从图上删除j点,让新源点接替所有j点具备的特征)
minlength += w; //当前最小生成树的总权值
m++;
}
return minlength;
}
int main()
{
int i = 0, j = 0,a=0,b=0,c=0;
memset(dist,inf,sizeof(dist));
cin>>N>>M;
for (i = 1; i <= M; i++)
{
cin >>a>>b>>c;
if(c<dist[a][b])
dist[a][b]=dist[b][a]=c;
}
cout << prim() << endl;
return 0;
}