最小生成树-QS Network(Prim)-LMLPHP最小生成树-QS Network(Prim)-LMLPHP最小生成树-QS Network(Prim)-LMLPHP最小生成树-QS Network(Prim)-LMLPHP

题目大意:

给出的案例结果得出步骤,如下图所示,从结点1开始查找,找出的一条路径如绿色部分所标注。(关键处在于连接每条路径所需要的适配器的价格得加上去)

最小生成树-QS Network(Prim)-LMLPHP

代码实现:

 #include<iostream>
#include<cstdio>
using namespace std;
#define MAX 1000
//注意此处范围得按照题意设置为>=1000,否则会Segmentation Fault
#define MAXCOST 0x7fffffff int graph[MAX][MAX]; int prim(int graph[][MAX], int n)
{
int lowcost[MAX];
int mst[MAX];
int i, j, min, minid, sum = ;
for (i = ; i <= n; i++)
{
lowcost[i] = graph[][i];
mst[i] = ;
}
mst[] = ;
for (i = ; i <= n; i++)
{
min = MAXCOST;
minid = ;
for (j = ; j <= n; j++)
{
if (lowcost[j] < min && lowcost[j] != )
{
min = lowcost[j];
minid = j;
}
}
sum += min;
lowcost[minid] = ;
for (j = ; j <= n; j++)
{
if (graph[minid][j] < lowcost[j])
{
lowcost[j] = graph[minid][j];
mst[j] = minid;
}
}
}
return sum;
} int main()
{
int i, j, k, t, en, n,x, y, cost,pre[];
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(i=;i<=n;i++)
scanf("%d",&pre[i]);
for (i = ; i <= n; i++)
{
for (j = ; j <= n; j++)
{
graph[i][j] = MAXCOST;
}
}
//构建图G
for(i = ; i <= n; i++){
for(k=;k<=n;k++){
scanf("%d",&graph[i][k]);
graph[i][k]+=pre[i];//直接将每条路径上存在的适配器价格给加到权值里面去即可
graph[i][k]+=pre[k];
}
}
cost = prim(graph, n);
cout <<cost << endl;
}
return ;
}
04-29 21:04