Cod sursa(job #3234753)

Utilizator drsbosDarius Scripcaru drsbos Data 11 iunie 2024 17:26:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <vector>
#include <bitset>
#include <fstream>
#include <algorithm>

using namespace std;

struct muchie
{
    int x, y, c;
    bool operator < (const muchie& other) const
    {
        return this->c < other.c;
    }
}E[400001];

int t[200001], r[200001], n, m;

void Read()
{
    ifstream fin("apm.in");
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
        fin >> E[i].x >> E[i].y >> E[i].c;
}

void Union(int x, int y)
{
    if (r[x] > r[y])
        t[y] = x;
    else {
        t[x] = y;
        if (r[x] == r[y])
            r[y]++;
    }
}

int Find(int x)
{
    if (t[x] == 0)
        return x;
    int y = Find(t[x]);
    t[x] = y;
    return y;
}

void Kruskal()
{
    sort(E + 1, E + m + 1);
    int totalcost = 0;
    vector <pair<int, int> > sol;
    for (int i = 1; i <= m; i++)
    {
        int x = Find(E[i].x);
        int y = Find(E[i].y);
        if (x != y)
        {
            Union(x, y);
            totalcost += E[i].c;
            sol.push_back({ E[i].x, E[i].y });
        }
    }
    ofstream fout("apm.out");
    fout << totalcost << "\n" << sol.size() << "\n";
    for (auto it : sol)
        fout << it.first << " " << it.second << "\n";
}

int main()
{
    Read();
    Kruskal();
    return 0;
}