Cod sursa(job #3277288)

Utilizator DragosVNVisanescu Dragos Nicholas DragosVN Data 15 februarie 2025 17:04:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
//problema facuta pe infoarena - arbore partial de cost minim
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
typedef pair<int,pair<int,int>>muchie;
vector <muchie>v;
queue<pair<int,int>>q;
int n,m,t[200005],S;
bool comp(muchie m1,muchie m2)
{
    return m1.first<m2.first;
}
void kruskal()
{
    int nrm=0;
    for(int i=0;i<m;i++)
    {
        int ex1=v[i].second.first,ex2=v[i].second.second,exc1=ex1,exc2=ex2;
        while(t[exc1]!=0)
        exc1=t[exc1];
        while(t[exc2]!=0)
            exc2=t[exc2];
        if(exc1!=exc2)
        {
            exc1=ex1;
            while(exc1!=0)
            {
                int c=exc1;
                exc1=t[exc1];
                t[c]=exc2;
            }
            S+=v[i].first;
            q.push(make_pair(ex2,ex1));
        }

    }
    g<<S<<'\n'<<n-1<<'\n';
    while(!q.empty())
    {
        g<<q.front().first<<" "<<q.front().second<<'\n';
        q.pop();
    }
}
int main()
{
    f>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        f>>x>>y>>c;
        v.push_back(make_pair(c,make_pair(x,y)));
    }
    sort(v.begin(),v.end(),comp);
    kruskal();
    return 0;
}