Cod sursa(job #2936349)

Utilizator andreii254andrei andreii254 Data 8 noiembrie 2022 18:01:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <algorithm>
using namespace std;

const int N = 2e5 + 1;

int n, m;
int T[N], rang[N];

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

vector <muchie> sol;

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;
    fin.close();
}

int Find(int x)
{
    if (T[x] == 0)
        return x;
    else
    {
        int k = Find(T[x]);
        T[x] = k;
        return k;
    }
}

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

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

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