Cod sursa(job #2124501)

Utilizator rangal3Tudor Anastasiei rangal3 Data 7 februarie 2018 11:47:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <cstdio>
#include <cctype>
#include <queue>
#define N 200003
#define BUF_SIZE 1000003

using namespace std;

FILE *fr = fopen("apm.in","r");
FILE *fw = fopen("apm.out","w");

char buf[BUF_SIZE];
int pos = BUF_SIZE;

inline char getChar()
{
    if(pos >= BUF_SIZE)
    {
        fread(buf,1,BUF_SIZE,fr);
        pos = 0;
    }

    return buf[pos++];
}

inline int Read()
{
    int neg;
    int sol = 0;
    char c;
    do
    {
        c = getChar();
    } while(!isdigit(c) && c != '-');

    if(c == '-')
    {
        c = getChar();
        neg = -1;
    }
    else neg = 1;


    do
    {
        sol = sol * 10 + c - '0';
        c = getChar();
    } while(isdigit(c));

    return sol*neg;
}

int n,m;
int c,x,y;
int TT[N];
pair<int,int> solm[N];
int cc[N];
priority_queue<pair<int, pair<int,int> > > q; //(-cost, (nod1,nod2))

inline int root(int nod)
{
    int urm,rad;
    rad = nod;
    while(TT[rad] != 0)
        rad = TT[rad];

    while(TT[nod] != 0)
    {
        urm = TT[nod];
        TT[nod] = rad;
        nod = urm;
    }
    return rad;
}

int main()
{
    n = Read();
    m = Read();

    //fprintf(fw,"%d %d",n,m);
    while(m--)
    {
        x = Read(); y = Read(); c = Read();
        q.push(make_pair(-c,make_pair(x,y)));
    }


    int cost,nod1,nod2;
    int sol = 0;
    int k = 0;
    int r1,r2;

    while(!q.empty())
    {
        nod1 = q.top().second.first;
        nod2 = q.top().second.second;
        cost = -q.top().first;

        r1 = root(nod1);
        r2 = root(nod2);
        q.pop();

        if(r1 != r2)
        {
            TT[r2] = r1;
            sol += cost;
            solm[++k].first = nod1;
            solm[k].second = nod2;
            cc[k] = cost;
        }

    }
    fprintf(fw,"%d\n%d\n",sol,n-1);

    for(int i=1; i<n; ++i)
        fprintf(fw,"%d %d\n",solm[i].first,solm[i].second,solm[i]);

    fclose(fr); fclose(fw);
    return 0;
}