poj2485

最小生成树

View Code
   
     
#include < iostream >
#include
< cstdio >
#include
< cstdlib >
#include
< cstring >
using namespace std;

#define maxn 505
#define inf 0x3f3f3f3f

int n, cost[maxn][maxn];
bool vis[maxn];
int lowcost[maxn];

void input()
{
scanf(
" %d " , & n);
for ( int i = 0 ; i < n; i ++ )
for ( int j = 0 ; j < n; j ++ )
scanf(
" %d " , & cost[i][j]);
}

int prim()
{
int ret = 0 , pre, best;

memset(vis,
0 , sizeof (vis));
for ( int i = 0 ; i < n; i ++ )
lowcost[i]
= inf;
lowcost[
0 ] = 0 ;
vis[
0 ] = true ;
pre
= 0 ;
while ( 1 )
{
for ( int i = 0 ; i < n; i ++ )
if ( ! vis[i] && lowcost[i] > cost[pre][i])
lowcost[i]
= cost[pre][i];
best
= inf;
pre
= - 1 ;
for ( int i = 0 ; i < n; i ++ )
if ( ! vis[i] && lowcost[i] < best)
{
pre
= i;
best
= lowcost[i];
}
if (pre == - 1 )
break ;
vis[pre]
= true ;
ret
= max(ret, lowcost[pre]);
lowcost[pre]
= 0 ;
}
return ret;
}

int main()
{
// freopen("t.txt", "r", stdin);
int t;
scanf(
" %d " , & t);
while (t -- )
{
input();
printf(
" %d\n " , prim());
}
return 0 ;
}

你可能感兴趣的:(poj)