Cod sursa(job #3155366)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 8 octombrie 2023 03:28:42
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <vector>

using namespace std;
using edge = pair<int, int>;

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

static constexpr int NMAX = (int)(2e5 + 1);
static const int INF = (int)(1e9);

int N, M;
vector<edge> G[NMAX];

static inline void read_edge()
{
    int x = 0, y = 0, u = 0;
    f >> x >> y >> u;

    G[x].push_back({u, y});
    G[y].push_back({u, x});

    return;
}

static inline void read()
{
    f.tie(nullptr);

    f >> N >> M;

    for (int i = 1; i <= M; ++i)
        read_edge();

    return;
}

int main()
{
    read();

    vector<int> ans, t = {};
    vector<bool> Sel = {};

    for (int i = 0; i <= N; ++i)
        ans.push_back(INF), t.push_back(-1), Sel.push_back(0);

    ans[1] = 0, Sel[1] = 1;
    for (auto &it : G[1])
        if (it.first < ans[it.second])
            ans[it.second] = it.first, t[it.second] = 1;

    int total_cost = 0;

    for (int i = 2; i <= N; ++i)
    {
        int Min = (INF + 1), pos = -1;

        for (int j = 1; j <= N; ++j)
            if (!Sel[j] && ans[j] < Min)
            {
                Min = ans[j];

                pos = j;
            }

        if (pos == -1)
            break;

        Sel[pos] = 1;

        total_cost += Min;

        for (auto &it : G[pos])
            if (!Sel[it.second] && it.first < ans[it.second])
                ans[it.second] = it.first, t[it.second] = pos;
    }

    g << total_cost << '\n'
      << (N - 1) << '\n';

    for (int i = 2; i <= N; ++i)
        g << t[i] << ' ' << i << '\n';

    return 0;
}