Cod sursa(job #2408209)

Utilizator Cezar211Popoveniuc Cezar Cezar211 Data 17 aprilie 2019 18:40:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
#define NM 200005
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
void read();
struct edge
{
    int x, y, c;
};
struct cmp
{
    bool operator()(const edge& a, const edge& b)
    {
        return a.c > b.c;
    }
};
priority_queue<edge, vector<edge>, cmp> q;
int n, m, t[NM], rang[NM], s[NM];
vector<pair<int,int>> sol;
int radacina(int p)
{
    if(t[p] == p)
        return p;
    else
        return (t[p] = radacina(t[p]));
}
int main()
{
    read();
    for(int i=1; i<=n; i++)
    {
        t[i] = i;
        rang[i] = 1;
    }
    while(!q.empty())
    {
        edge cur = q.top();
        q.pop();
        int rx = radacina(cur.x), ry = radacina(cur.y);
        if(rx!=ry)
        {
            sol.push_back({cur.x, cur.y});
            if(rang[rx] > rang[ry])
            {
                t[ry] = rx;
                s[rx]+=s[ry]+cur.c;
            }
            else
            {
                t[rx] = ry;
                s[ry]+=s[rx]+cur.c;
                if(rang[rx] == rang[ry])
                    rang[ry]++;
            }
        }
    }
    fout << s[radacina(1)] << '\n' << n-1 << '\n';
    for(auto it : sol)
        fout << it.second << ' ' << it.first << '\n';
    return 0;
}
void read()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        q.push({x, y, c});
    }
}