Cod sursa(job #2737768)

Utilizator inwursuIanis-Vlad Ursu inwursu Data 5 aprilie 2021 08:39:54
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
// Kruskal.cpp : This file contains the 'main' function. Program execution begins and ends there.

#include <iostream>
#include <vector>
#include <fstream>
#include <tuple>
#include <algorithm>

using namespace std;

const int N_MAX = 200000 + 1;
const int M_MAX = 400000 + 1;

int N, M;
vector<tuple<int, int, int>> edges;



int parent[N_MAX];
int cardinal[N_MAX];

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

    return parent[x] = find_root(parent[x]);
}

void merge_sets(int x, int y)
{
    int root_x = find_root(x);
    int root_y = find_root(y);

    if (root_x == root_y) return;

    if (cardinal[root_x] < cardinal[root_y])
    {
        swap(root_x, root_y);
    }

    parent[root_y] = root_x;
    cardinal[root_x] += cardinal[root_y];
    cardinal[root_y] = 0;
}


vector<tuple<int, int>> apm_edges;


int main()
{
    ifstream fin{ "apm.in" };
    ofstream fout{ "apm.out" };

    fin >> N >> M;

    for (int i = 1; i <= M; ++i)
    {
        int u, v, weight;
        fin >> u >> v >> weight;

        edges.push_back({ u, v, weight });
    }

    sort(edges.begin(), edges.end(), [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {
        return get<2>(a) < get<2>(b);
    });


    long long apm_weight{ 0 };


    for (int i = 0; i < M; ++i)
    {
        int u = get<0>(edges[i]);
        int v = get<1>(edges[i]);
        int weight = get<2>(edges[i]);

        if (find_root(u) != find_root(v))
        {
            apm_edges.push_back({ u, v });
            apm_weight += weight;

            merge_sets(u, v);
        }
    }


    fout << apm_weight << "\n";


    for (const auto& edge : apm_edges)
    {
        int u = get<0>(edge);
        int v = get<1>(edge);

        fout << u << " " << v << endl;
    }
}