(Prim算法)codeVs 1078 最小生成树

时间:2023-03-09 05:52:13
(Prim算法)codeVs 1078 最小生成树
题目描述 Description

农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。 约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了使花费最少,他想铺设最短的光纤去连接所有的农场。 你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。 每两个农场间的距离不会超过100000

输入描述 Input Description

第一行: 农场的个数,N(3<=N<=100)。

第二行..结尾: 接下来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们每行限制在80个字符以内,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为线路从第i个农场到它本身的距离在本题中没有意义。

输出描述 Output Description

只有一个输出,是连接到每个农场的光纤的最小长度和。

样例输入 Sample Input

4

0  4  9 21

4  0  8 17

9  8  0 16

21 17 16  0

样例输出 Sample Output

28

Prim算法模板题

Prim算法是一个贪心算法,原理呢。。。。=》参考书目:《算法导论》《趣学算法》

C++代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = ;
bool s[N];
int closest[N];
int lowcost[N];
int c[N][N];
void Prim(int n, int u0, int c[N][N]){
s[u0] = true;
int i,j;
for(i = ; i <= n; i++){
if(i!=u0){
lowcost[i] = c[u0][i];
closest[i] = u0;
s[i] = false;
}
else{
lowcost[i] = ;
}
}
for(i = ; i <= n; i++){
int temp = INF;
int t = u0;
for(j = ; j <= n; j++){
if(!s[j] && (lowcost[j] < temp)){
t = j;
temp = lowcost[j];
}
}
if(t == u0) break;
s[t] = true;
for(j = ; j <= n; j++){
if((!s[j]) && (c[t][j] < lowcost[j])){
lowcost[j] = c[t][j];
closest[j] = t;
}
}
}
}
int main(){
int n;
cin>>n;
for(int i = ; i <= n; i++){
for(int j = ; j <= n; j++){
cin>>c[i][j];
}
}
Prim(n,,c);
int sum = ;
for(int i = ; i <= n; i++)
sum+=lowcost[i];
cout<<sum<<endl;
return ;
}