Cod sursa(job #1609385)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 22 februarie 2016 19:29:06
Problema Arbore partial de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <algorithm>
#include <queue>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

int j, t[200010], C, k, N, M;
queue<int> Q;

struct muchie
{
    int a;
    int b;
    int c;

} v[400010], E[400010];

bool cmp(const muchie &x, const muchie &y)
{
    return x.c < y.c;
}

void update(int x, int y)
{
    while(t[x] > 0)
    {
        Q.push(x);
        x = t[x];
    }
    while(t[y] > 0)
    {
        Q.push(y);
        y = t[y];
    }

    if(x != y)
    {
        if(t[x] <= t[y])
        {
            t[x] += t[y];
            t[y] = x;
            while(!Q.empty())
            {
                t[Q.front()] = x;
                Q.pop();
            }
        }
        else
        {
            t[y] += t[x];
            t[x] = y;
            while(!Q.empty())

            {
                t[Q.front()] = y;
                Q.pop();
            }
        }

        C += v[j].c;
        E[++k] = v[j];
    }
}

int main()
{
    fin >> N >> M;

    for(int i = 1; i <= N; i ++)
    {
        t[i] = -1;
    }

    for(int i = 1; i <= M; i ++)
    {
        fin >> v[i].a >> v[i].b >> v[i].c;
    }

    sort(v + 1, v + M + 1, cmp);

    for(j = 1; j <= M; j ++)
    {
        update(v[j].a, v[j].b);
    }

    for(int i = 1; i <= N; i ++)
    {
        if(t[i] < 0)
        {
            fout << C << '\n' << -(t[i] + 1) << '\n';
            break;
        }
    }

    for(int i = 1; i <= k; i ++)
    {
        fout << E[i].a << " " << E[i].b << '\n';
    }


    return 0;
}