题目链接:
https://vjudge.net/problem/POJ-1258
题目大意:
求MST
思路:
由于给的是邻接矩阵,直接prim算法
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<sstream>
using namespace std;
typedef long long ll;
const int maxn = 2e3 + ;
const int INF = << ;
int dir[][] = {,,,,-,,,-};
int T, n, m, x;
int Map[maxn][maxn];//存图
int lowcost[maxn], mst[maxn];
void prim(int u)//最小生成树起点
{
int sum_mst = ;//最小生成树权值
for(int i = ; i <= n; i++)//初始化两个数组
{
lowcost[i] = Map[u][i];
mst[i] = u;
}
mst[u] = -;//设置成-1表示已经加入mst
for(int i = ; i <= n; i++)
{
int minn = INF;
int v = -;
//在lowcost数组中寻找未加入mst的最小值
for(int j = ; j <= n; j++)
{
if(mst[j] != - && lowcost[j] < minn)
{
v = j;
minn = lowcost[j];
}
}
if(v != -)//v=-1表示未找到最小的边,
{//v表示当前距离mst最短的点
//printf("%d %d %d\n", mst[v], v, lowcost[v]);//输出路径
mst[v] = -;
sum_mst += lowcost[v];
for(int j = ; j <= n; j++)//更新最短边
{
if(mst[j] != - && lowcost[j] > Map[v][j])
{
lowcost[j] = Map[v][j];
mst[j] = v;
}
}
}
}
//printf("weight of mst is %d\n", sum_mst);
cout<<sum_mst<<endl;
}
int main()
{
while(cin >> n && n)
{
for(int i = ; i <= n; i++)
{
for(int j = ; j <= n; j++)
scanf("%d", &Map[i][j]);
}
prim();
} return ;
}