ZOJ-1586 QS Network---最小生成树Prim

时间:2023-03-09 00:49:44
ZOJ-1586 QS Network---最小生成树Prim

题目链接:

https://vjudge.net/problem/ZOJ-1586

题目大意:

首先给一个t,代表t个测试样例,再给一个n,表示有n个QS装置,接下来一行是n个QS装置的成本。接下来是n*n的矩阵,表示每两个QS 装置之间链接需要的费用。求在全联通的情况下求最少费用。

思路:

这里需要求最少费用,由于点和边都有权值,索性直接把两端点的权值加到边的权值上,那就变成了一个裸的MST题目了

 #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];
int a[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()
{
cin >> T;
while(T--)
{
cin >> n;
for(int i = ; i <= n; i++)cin >> a[i];
for(int i = ; i <= n; i++)
{
for(int j= ; j <= n; j++)
{
cin >> Map[i][j];
if(i == j)continue;
Map[i][j] += a[i] + a[j];//把两个端点的权值加在边上,就转变成裸的MST题目了
}
}
prim();
}
return ;
}