Cod sursa(job #2556493)

Utilizator razvanradulescuRadulescu Razvan razvanradulescu Data 24 februarie 2020 22:33:06
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <algorithm>
using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

struct muchii
{
    int x, y, cost;

    operator <(muchii other)
    {
        return cost < other.cost;
    }
};

int tati[200005], n, m, sum;
muchii graf[400005], rez[200005];
int addedEdges = 0;

int getRoot(int x)
{
    if(tati[x] == 0)
        return x;
    tati[x] = getRoot(tati[x]);
    return tati[x];
}

void read()
{
    f>>n>>m;
    for(int i = 0; i<m; ++i)
    {
        f>>graf[i].x>>graf[i].y>>graf[i].cost;
    }
    sort(graf, graf+m);
}

void solve()
{
    int xRoot, yRoot;
    for(int k = 0; addedEdges < n-1 && k < m; ++k)
    {
        xRoot = getRoot(graf[k].x);
        yRoot = getRoot(graf[k].y);
        if(xRoot != yRoot)
        {
            tati[xRoot] = yRoot;
            sum += graf[k].cost;
            rez[addedEdges++] = graf[k];
        }
    }
}

void print()
{
    g<<sum<<"\n";
    g<<addedEdges<<"\n";
    for(int i = 0; i<addedEdges; ++i)
    {
        g<<rez[i].x<<" "<<rez[i].y<<"\n";
    }
}

int main()
{
    read();
    solve();
    print();
    return 0;
}