Cod sursa(job #3259708)

Utilizator TonyyAntonie Danoiu Tonyy Data 27 noiembrie 2024 16:28:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>
#define tp tuple<int,int,int>
#define pr pair<int,int>
using namespace std;

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

int n, m, x, y, c, cost;
const int Max = 2e5 + 1;
vector<tp> edges;
vector<pr> mst;
vector<int> parent(Max, -1), d(Max, 1);

int find_set(int x)
{
    if(parent[x] == -1)
        return x;
    return parent[x] = find_set(parent[x]);
}

void union_sets(int x, int y)
{
    x = find_set(x);
    y = find_set(y);
    if(x == y)
        return;
    if(d[x] < d[y])
        swap(x, y);
    parent[y] = x;
    d[x] += d[y];
}

struct compare
{
    bool operator()(tuple<int,int,int> x, tuple<int,int,int> y)
    {
        return get<2>(x) < get<2>(y);
    }
};

void kruskal()
{
    sort(edges.begin(), edges.end(), compare());
    for(auto i: edges)
    {
        tie(x, y, c) = i;
        if(find_set(x) != find_set(y))
        {
            union_sets(x, y);
            mst.push_back({x, y});
            cost += c;
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    fin.tie(NULL);

    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        edges.push_back({x, y, c});
    }
    kruskal();
    fout << cost << "\n" << n - 1 << "\n";
    for(auto i: mst)
    {
        fout << i.first << " " << i.second << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}