Cod sursa(job #2375979)

Utilizator NannyiMaslinca Alecsandru Mihai Nannyi Data 8 martie 2019 13:12:17
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
using namespace std;
#define nmax 200005

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

int n,m,p[nmax],tcost;

int parent(int x)
{
    if (x==p[x])
        return x;
    return p[x]=parent(p[x]);
}

void unity(int x,int y)
{
    p[parent(x)]=parent(y);
}

struct str
{
    int x,y,cost;
    bool operator <(const str &a)const
    {
        return cost>a.cost;
    }
};
vector<pair<int,int>>edges;
priority_queue<str>Q;

void read()
{
    f>>n>>m;
    for (int i=1; i<=m; ++i)
    {
        int l1,l2,l3;
        f>>l1>>l2>>l3;
        Q.push({l1,l2,l3});
    }
}

void solve()
{
    for (int i=1;i<=n;++i)
        p[i]=i;
    while (!Q.empty())
    {
        int x=Q.top().x;
        int y=Q.top().y;
        int cost=Q.top().cost;
        Q.pop();
        if (parent(x)==parent(y))
            continue;
        unity(x,y);
        tcost+=cost;
        edges.push_back({x,y});
    }
    g<<tcost<<'\n'<<edges.size()<<'\n';
    for (auto w:edges)
        g<<w.first<<' '<<w.second<<'\n';
}

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