BZOJ 1601: [Usaco2008 Oct]灌水( MST )
MST , kruskal 直接跑
----------------------------------------------------------------------
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>
#include<iostream>
#define rep( i , n ) for( int i = 0 ; i < n ; ++i )
#define clr( x , c ) memset( x , c , sizeof( x ) )
#define Rep( i , n ) for( int i = 1 ; i <= n ; ++i )
using namespace std;
const int maxn = 300 + 5;
struct edge {
int u , v , w;
bool operator < ( const edge &e ) const {
return w < e.w;
}
};
vector< edge > E;
int p[ maxn ];
int find( int x ) {
return x == p[ x ] ? x : p[ x ] = find( p[ x ] );
}
long long kruskal( int n ) {
rep( i , n ) p[ i ] = i;
sort( E.begin() , E.end() );
long long ans = 0;
rep( i , E.size() ) {
edge* e = &E[ i ];
int a = find( e -> u ) , b = find( e -> v );
if( a != b )
p[ a ] = b , ans += e -> w;
}
return ans;
}
int main() {
// freopen( "test.in" , "r" , stdin );
int n;
cin >> n;
Rep( i , n ) {
int w;
scanf( "%d" , &w );
E.push_back( ( edge ) { 0 , i , w } );
}
Rep( i , n )
Rep( j , n ) {
int w;
scanf( "%d" , &w );
if( i != j ) E.push_back( ( edge ) { i , j , w } );
}
cout << kruskal( n + 1 ) << "\n";
return 0;
}
----------------------------------------------------------------------