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 , M = 210 ;
const int INF = 0x3f3f3f3f ;
int n , m ; // n条顶点,m条边
int res ; // 最小生成树的权值和
int cnt ; // 最小生成树的结点数
// Kruskal用到的结构体
struct Node {
int a , b , c ;
bool const operator < ( const Node & t ) const {
return c < t . c ; // 边权小的在前
}
} edge [ M ] ; // 数组长度为是边数
// 并查集
int p [ N ] ;
int find ( int x ) {
if ( p [ x ] ! = x ) p [ x ] = find ( p [ x ] ) ;
return p [ x ] ;
}
// Kruskal算法
void kruskal ( ) {
// 1、按边权由小到大排序
sort ( edge , edge + m ) ;
// 2、并查集初始化
for ( int i = 1 ; i < = n ; i + + ) p [ i ] = i ;
// 3、迭代m次
for ( int i = 0 ; i < m ; i + + ) {
int a = edge [ i ] . a , b = edge [ i ] . b , c = edge [ i ] . c ;
a = find ( a ) , b = find ( b ) ;
if ( a ! = b )
p [ a ] = b , res + = c , cnt + + ; // cnt是指已经连接上边的数量
}
// 这句话需要注释掉,原因如下:
/*
6 6
1 2 5
1 3 4
2 3 8
4 5 7
4 6 2
5 6 1
我们发现, 1,2,3是一伙, 4,5,6是另一伙, 这两个家庭不通! 如果按照模板的意思, 那么就没有最小生成树!
这么说是没有问题的,但本题不是求最小生成树,而是求最小生成森林!所以,下面的特判需要注释掉!
*/
// 4、特判是不是不连通
// if (cnt < n - 1) res = INF;
}
int main ( ) {
cin > > n > > m ;
int sum = 0 ;
// Kruskal算法直接记录结构体
for ( int i = 0 ; i < m ; i + + ) {
int a , b , c ;
cin > > a > > b > > c ;
edge [ i ] = { a , b , c } ;
sum + = c ;
}
kruskal ( ) ;
printf ( " %d \n " , sum - res ) ;
return 0 ;
}