Cod sursa(job #3203479)

Utilizator tudor_bustanBustan Tudor Gabriel tudor_bustan Data 13 februarie 2024 18:50:44
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#define inf INT_MAX
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{
    int x, y, c;
    bool operator < (const muchie &alta) const
    {
        return c<alta.c;
    }
};
int n, m, x, y, c, viz[200009], height[200009], cost;
vector <muchie> M, sol;
int fnd(int x)
{
    if(x!=viz[x])
    {
        return fnd(viz[x]);
    }
    return viz[x];
}
void uneste(int a, int b)
{
    a=fnd(a), b=fnd(b);
    if(height[a]<height[b])
    {
        viz[a]=b;
    }
    else viz[b]=a;
    if(height[a]==height[b])
    {
        height[b]++;
    }
}
void kruskal()
{
    for(int i=1; i<=n; i++)
    {
        viz[i]=i;
        height[i]=1;
    }
    for(auto &e:M)
    {
        if(fnd(e.x)!=fnd(e.y))
        {
            uneste(e.x, e.y);
            cost+=e.c;
            sol.push_back(e);
            muchii++;
        }
    }
}
int main()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        M.push_back({x, y, c});
        M.push_back({y, x, c});
    }
    sort(M.begin(), M.end());
    kruskal();
    fout<<cost<<"\n"<<sol.size()<<"\n";
    for(auto &s:sol)
    {
        fout<<s.x<<" "<<s.y<<"\n";
    }
    return 0;
}