Cod sursa(job #460268)

Utilizator BitOneSAlexandru BitOne Data 1 iunie 2010 19:47:33
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <algorithm>
#define Nmax 200111

/*
 *
 */
using namespace std;
struct pr
{
    int x, y, c;
};
int f[Nmax], r[Nmax];
vector< pr > v, apm;
inline int find( int x )
{
    int y, z;
    for( y=x; y != f[y]; y=f[y] );
    while( 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]=( r[x] <= r[y] ? r[x] : r[y] );
}
inline bool operator<( const pr& x, const pr& y )
{
        return ( y.c > x.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;
}
int main( void )
{
    int N, M, i, j, fx, fy, s;
    ifstream in( "apm.in" );
    in>>N>>M;
    for( i=1; i <= N; ++i )
        f[i]=i, r[i]=1;
    copy( istream_iterator< pr >( in ), istream_iterator< pr >(), back_inserter(v) );
    sort( v.begin(), v.end() );
    for( i=N-1, s=j=0; i; ++j )
    {
        fx=find( v[j].x );
        fy=find( v[j].y );
        if( fx != fy )
        {
            --i;
            s+=v[j].c;
            unite( fx, fy );
            apm.push_back( v[j] );
        }
    }
    ofstream out( "apm.out" );
    out<<s<<'\n'<<apm.size()<<'\n';
    copy( apm.begin(), apm.end(), ostream_iterator<pr>( out ) );
    out<<'\n';
    return EXIT_SUCCESS;
}