You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <bits/stdc++.h>
using namespace std ;
const int N = 110 ;
int n ;
int g [ N ] [ N ] ; // 邻接矩阵,记录每两个点之间的距离
int dis [ N ] ; // 每个点距离集合的最小长度
bool st [ N ] ; // 是不是已经加入到集合中
int prim ( ) {
// 初始化所有节点到集合的距离为正无穷
memset ( dis , 0x3f , sizeof dis ) ;
dis [ 1 ] = 0 ; // 1号节点到集合的距离为0
int res = 0 ;
for ( int i = 1 ; i < = n ; i + + ) { // 迭代n次
int t = - 1 ;
//(1)是不是第一次
//(2)如果不是第1次那么找出距离最近的那个点j
for ( int j = 1 ; j < = n ; j + + )
if ( ! st [ j ] & & ( t = = - 1 | | dis [ t ] > dis [ j ] ) ) // 第一次就是猴子选大王,赶鸭子上架
t = j ;
// 最小生成树的距离和增加dis[t]
res + = dis [ t ] ;
// t节点入集合
st [ t ] = true ;
// 利用t, 拉近其它节点长度
for ( int j = 1 ; j < = n ; j + + ) dis [ j ] = min ( dis [ j ] , g [ t ] [ j ] ) ;
}
return res ;
}
int main ( ) {
cin > > n ;
// 完全图,每两个点之间都有距离,不用考虑无解情况
for ( int i = 1 ; i < = n ; i + + )
for ( int j = 1 ; j < = n ; j + + )
cin > > g [ i ] [ j ] ;
// 利用prim算法计算最小生成树
cout < < prim ( ) < < endl ;
return 0 ;
}