HDU 1863 畅通工程

读入边权要注意是否比原来的边权小

  
    
#include < iostream >
#include
< fstream >
#include
< string .h >
using namespace std;
const int MAXN = 1000 ;
int G[MAXN][MAXN];
int lowcost[MAXN];
int cloest[MAXN];
bool used[MAXN];
int cost;

void PRIM( int n){
int cnt = 0 ;
cost
= 0 ;
used[
1 ] = true ;
for ( int i = 2 ; i <= n; i ++ ){
lowcost[i]
= G[i][ 1 ];
cloest[i]
= 1 ;
used[i]
= false ;
}
for ( int i = 1 ; i < n; i ++ ){
int min = 32767 , minIndex = i;
for ( int j = 1 ; j <= n; j ++ ){
if ( ! used[j] && lowcost[j] < min){
min
= lowcost[j];
minIndex
= j;
}
}
if (min == 32767 ){
break ;
}
cost
+= min;
used[minIndex]
= true ;
cnt
++ ;
for ( int j = 1 ; j <= n; j ++ ){
if ( ! used[j] && lowcost[j] > G[minIndex][j]){
lowcost[j]
= G[minIndex][j];
cloest[j]
= minIndex;
}
}
}
if ( cnt != n - 1 )
cout
<< " ? " << endl;
else
cout
<< cost << endl;
}

int main(){
int n, m, x, y, weight;
while (cin >> n >> m){
if ( n == 0 )
break ;
// memset(G,32767,sizeof(G));
for ( int i = 0 ; i < 1000 ; ++ i)
for ( int j = 0 ; j < 1000 ; ++ j){
G[i][j]
= 32767 ;
}
for ( int i = 1 ; i <= n;i ++ ){
cin
>> x >> y >> weight;
G[x][y]
= G[x][y] < weight ? G[x][y]:weight; // 陷阱
G[y][x] = G[x][y];
// G[x][y] = G[x][y] < weight ? G[x][y]:weight;
// G[y][x] = G[x][y] = weight;
}
// cout << cost << endl;
if ( n < m - 1 )
cout
<< " ? " << endl;
else
PRIM(m);
}
return 0 ;
}

你可能感兴趣的:(HDU)