Cod sursa(job #376714)

Utilizator alexandru92alexandru alexandru92 Data 22 decembrie 2009 12:52:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on December 22, 2009, 12:28 PM
 */
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>

/*
 * 
 */
using namespace std;
vector<unsigned int> rank, father;
inline unsigned int find( unsigned int x )
{unsigned int y, z;
    for( y=x; father[y] != y; y=father[y] );
    while( father[x] != x )
    {
        z=father[x];
        father[x]=y;
        x=z;
    }
    return y;
}
inline void Union( unsigned int x, unsigned int y )
{
    if( rank[x] == rank[y] )
    {
        if( x != y )
            father[y]=x;
        ++rank[y];
    }
    else rank[x]=rank[y]=min( rank[x], rank[y] );
}
struct vertex
{
    int c;
    unsigned int x, y;
};
inline istream& operator>>( istream& in, vertex& A )
{
    in>>A.x>>A.y>>A.c;
    return in;
}
inline ostream& operator<<( ostream& out, vertex A )
{
    out<<A.x<<' '<<A.y<<'\n';
    return out;
}
inline bool cmp( vertex A, vertex B )
{
    return A.c < B.c;
}
vector<vertex> apm, v;
int main()
{int s=0;
 unsigned int n, m, i, xf, yf;
    ifstream in("apm.in");
    in>>n>>m;
    copy( istream_iterator<vertex>(in), istream_iterator<vertex>(), back_inserter(v) );
    sort( v.begin(), v.end(), cmp );
    father.resize(n);
    rank.resize(n);
    for( i=0; i < n ; father[i]=i, ++i );
    for( i=0; i < m && n > 0; ++i )
    {
        xf=find( v[i].x-1 );
        yf=find( v[i].y -1 );
        if( xf != yf )
        {--n;
            s+=v[i].c;
            apm.push_back(v[i]);
            Union( xf, yf );
        }
    }
    ofstream out("apm.out");
    out<<s<<' '<<apm.size()<<'\n';
    copy( apm.begin(), apm.end(), ostream_iterator<vertex>(out) );
    return 0;
}