Cod sursa(job #2945536)

Utilizator BetJohn000Ioan Benescu BetJohn000 Data 23 noiembrie 2022 21:10:23
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>

using namespace std;
// rezolvare APM cu Kruskal
// O(E log E) = O(E log V)
// E = numarul de muchii
// V = numarul de noduri
//pas1: sortam muchiile crescator dupa cost
//pas2: parcurgem muchiile in ordine crescatoare
//      daca muchia curenta nu formeaza ciclu cu multimea APM curenta
//      o adaugam in APM
//      altfel o ignoram
//pas3: afisam APM
ifstream f("apm.in");
ofstream g("apm.out");
const int NMAX = 100005;
const int MMAX = 100005;
int N, M, Total, TT[MMAX],RG[MMAX],k;
struct Muchie
{
    int x, y, cost;
} V[MMAX];
pair <int, int> P[MMAX];
bool compare(Muchie a, Muchie b)
{
    return a.cost < b.cost;
}
void read()
{
    f >> N >> M;
    for (int i = 1; i <= M; i++)
        f >> V[i].x >> V[i].y >> V[i].cost;
    //sortam muchiile crescator dupa cost
    sort(V + 1, V + M + 1, compare);
    for(int i = 1;i<=N;i++)
        {
            TT[i] = i;
            RG[i] = 1;
        }
}
int Find(int Nod)
{
    if (TT[Nod] == Nod)
        return Nod;
    return TT[Nod] = Find(TT[Nod]);
}
void Unire(int x, int y)
{
    if(RG[x] > RG[y])
        TT[y] = x;
    if(RG[x] < RG[y])
        TT[x] = y;
    if(RG[x] == RG[y])
    {
        TT[x] = y;
        RG[y]++;
    }

}
void Rezolvare()
{
    for(int i=1;i<=M;i++)
    {
        int tatal_x = Find(V[i].x);
        int tatal_y = Find(V[i].y);

        if(tatal_x != tatal_y)
        {
            Unire(tatal_x,tatal_y);
            P[++k].first = V[i].x;
            P[k].second = V[i].y;
            Total += V[i].cost;  
        }
    }
}
void afisare()
{
    g << Total << endl;
    g << N - 1 << endl;
    
    for(int i=1;i<=k;i++)
        g << P[i].first << " " << P[i].second << endl;
}
int main()
{
    read();
    Rezolvare();
    afisare();
    return 0;
}