poj 2485 Highways

一道简单的最小生成树问题;

View Code
#include<iostream>

#include<cstdio>

#include<cstdlib>

#include<algorithm>

#include<cmath>

#include<queue>

#include<map>

#include<cstring>

#include<vector>

using namespace std;

class Kru

{

public:

      int x,y,dis;

}kru[250024];

int set[524];

bool cmp(Kru a , Kru b )

{

    return a.dis < b.dis;    

}

int find( int x )

{

   return set[x] == x ? x : set[x] = find( set[x] );    

}

int Kruscal( int N )

{

  int ans,X,Y;

  for( int i = 0 ; i < N ; i++ )

  {

     if( ( X = find( kru[i].x ) )!=( Y = find(kru[i].y) ) )

     {

         ans = kru[i].dis;

         set[Y] =X;        

     }

  }    

  return ans;

}

int main(  )

{

     int N,Case,dis;

     while( scanf( "%d",&Case )==1 )

     {

         while( Case -- )

         {

             int count = 0 ;

             scanf( "%d",&N );

             for( int i = 1 ; i <= N ; i++ )

             {

                set[i] = i;

                for( int j = 1 ; j <= N; j ++ )

                {

                     scanf( "%d",&dis );

                     kru[count].x = i;kru[count].y=j;

                     kru[count++].dis = dis;    

                }    

             }

             sort( kru ,kru + count , cmp );

             printf( "%d\n",Kruscal( count ) );        

         }        

     }

    //system( "pause" );

    return 0;

}

 

你可能感兴趣的:(poj)