Cod sursa(job #3338564)

Utilizator todoranstefaniaTodoran Stefania todoranstefania Data 3 februarie 2026 22:44:52
Problema Arbore partial de cost minim Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <fstream>
using namespace std;
int n, m;
ifstream fin("apm.in");
ofstream fout("apm.out");
vector < vector<int> > G,Arb;
void citire()
{
    int x,y,cost;
    fin>>n>>m;
    for(int i=1; i<=m; i++){
        fin>>x>>y>>cost;
        G.push_back({cost,x,y});
    }
}
int cc[200005];
void uneste(int x, int y)
{
    for(int i=1; i<=n; i++)
        if(cc[i]==y)
            cc[i]=x;
}
void kruskal()
{
    long long costTotal=0,nrm=0;
    sort(G.begin(),G.end());
    for(int i=1; i<=n; i++)
        cc[i]=i;
    for(auto muchie : G)
    {
        int cost = muchie[0], x=muchie[1], y=muchie[2];
        if(cc[x]==cc[y])
            continue;
        costTotal+=cost;
        Arb.push_back(muchie);
        uneste(cc[x],cc[y]);
        if(nrm==n-1)
            break;
    }
    fout<<costTotal<<"\n";
    fout<<Arb.size()<<"\n";
    for(auto muchie:Arb)
        fout<<muchie[1]<<" "<<muchie[2]<<"\n";
}
int main()
{
    citire();
    kruskal();
    return 0;
}