HDU 1102 Constructing Roads

基础的最小生成树 有的路已经建好了,就把矩阵置0 就可以了

  
    
// prim MST
#include < stdio.h >
#include
< stdlib.h >
#include
< string .h >
int G[ 101 ][ 101 ];
bool used[ 101 ];
int lowcost[ 101 ];
int closest[ 101 ];
int cost;

void prim( int n){
cost
= 0 ;
used[
1 ] = true ;
int minj;
for ( int i = 2 ; i <= n; i ++ ){
lowcost[i]
= G[i][ 1 ];
closest[i]
= 1 ;
used[i]
= false ;
}
for ( int i = 1 ; i < n; i ++ ){ // n-1次
int min = 32767 ;
for ( int k = 1 ; k <= n; k ++ ){
if ( ! used[k] && lowcost[k] < min ){
min
= lowcost[k];
minj
= k;
}
}
used[minj]
= true ;
cost
+= min;
for ( int j = 1 ; j <= n;j ++ ){
if ( ! used[j] && G[minj][j] < lowcost[j])
lowcost[j]
= G[minj][j];
}
}
}

int main(){
int N,Q,x,y;
while (scanf( " %d " , & N) == 1 ){
for ( int i = 1 ; i <= N;i ++ )
for ( int j = 1 ; j <= N; j ++ )
scanf(
" %d " , & G[i][j]);
scanf(
" %d " , & Q);
// 有连线的 将G[x][y] 置0
while (Q -- ){
scanf(
" %d %d " , & x, & y);
G[x][y]
= 0 ;
G[y][x]
= 0 ;
}
prim(N);
printf(
" %d\n " ,cost);
}
return 0 ;
}

你可能感兴趣的:(struct)