Cod sursa(job #451358)

Utilizator alexandru92alexandru alexandru92 Data 9 mai 2010 14:24:12
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on May 9, 2010, 2:01 PM
 */
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <algorithm>
#define Nmax 200011

/*
 * 
 */
using namespace std;
int f[Nmax], r[Nmax];
struct pr
{
    int x, y, c;
    pr( void ) : x(0), y(0), c(0x3f3f3f3f) {};
} v[2*Nmax], apm[Nmax];
inline bool operator<( const pr& x, const pr& y )
{
    return x.c < y.c;
}
inline istream& operator>>( istream& in,  pr& x )
{
    in>>x.x>>x.y>>x.c;
    return in;
}
inline ostream& operator<<( ostream& out, const pr& x )
{
    out<<x.x<<' '<<x.y<<'\n';
    return out;
}
inline int find( int x )
{
    int y, z;
    for( y=x; y != f[y]; y=f[y] );
    for( ; x != f[x]; )
    {
        z=f[x];
        f[x]=y;
        x=z;
    }
    return y;
}
inline void Unite( int x, int y )
{
    if( r[x] == r[y] )
    {
        if( x != y )
            f[y]=x;
        ++r[y];
    }
    else r[x]=r[y]=min( r[x], r[y] );
}
int main(int argc, char** argv)
{
    int N, M, i, j, x, y, s;
    ifstream in( "apm.in" );
    in>>N>>M;
    for( i=1; i <= M; ++i )
    {
        in>>v[i];
        if( i <= N )
            f[i]=i, r[i]=1;
    }
    sort( v+1, v+M+1 );
    for( s=j=0, i=1; j < N-1; ++i )
    {
        x=find(v[i].x);
        y=find(v[i].y);
        if( x != y )
        {
            s+=v[i].c;
            Unite( x, y );
            apm[++j]=v[i];
        }
    }
    ofstream out( "apm.out" );
    out<<(s)<<' '<<(N-1)<<'\n';
    copy( apm+1, apm+N, ostream_iterator< pr >( out ) );
    return (EXIT_SUCCESS);
}