ural Network ( 最小生成树)

题意:有N台电脑,它们之间可以相连的线路由M条,现在让你求将所有电脑连起来的所有方案中,哪个方案中最长的一段线路最短。

其实这题和poj的2253有些类似,刚开始的时候我甚至就改了改那题的代码交上去,结果WA了,后来又看了一遍样例,这题要求的是将所有电脑都连起来,也就是说,符合要求的方案必须是包含所有电脑的,这和2253不同,2253只是求从起点到终点的一条路,而这题是求最小生成树的,我用的是Kruskal,还有,虽然题目中没说,但这题是multiple answers。

代码:

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <math.h>
#define  N 15004
#define  INF 100000000
using namespace std ;

struct node
{
    int from ;
    int to ;
    int val ;
}p[N] ;
int f[N] ;

bool cmp( node a , node b )
{
    if ( a.val < b.val )
    return true ;
    else
    return false ;
}

void init()
{
    int i ;
    for ( i = 0 ; i < N ; i++ )
    f[i] = i ;
}

int find( int x )
{
    if ( x != f[x] )
    f[x] = find( f[x] ) ;
    return f[x] ;
}

int main()
{
    int n , m , i , x , y , min_len , s ;
    int path[N] ;

    while( scanf ( "%d%d" , &n , &m ) != EOF )
    {
        for ( i = 0 ; i < m ; i++ )
        {
            scanf ( "%d%d%d" , &p[i].from , &p[i].to , &p[i].val );
        }
        sort( p , p + m , cmp ) ;
        /*for ( i = 0 ; i < m ; i++ )
        cout<<p[i].from<<" "<<p[i].to<<endl;*/
        init() ;
        min_len = 0 ;
        s = 0 ;
        for ( i = 0 ; i < m ; i++ )
        {
            x = find( p[i].from ) ;
            y = find( p[i].to );
            if ( x != y )
            {
                f[x] = y ;
                path[s++] = i ;
                if ( p[i].val > min_len )
                min_len = p[i].val ;
            }
        }
        cout<<min_len<<endl ;
        cout<<s<<endl ;
        for ( i = 0 ; i < s ; i++ )
        {
            printf ( "%d %d\n" , p[path[i]].from , p[path[i]].to ) ;
        }
    }
    return 0 ;
}
原文地址:https://www.cnblogs.com/misty1/p/2951176.html