Cod sursa(job #2808051)

Utilizator rimihaiMihai Radu-Ioan rimihai Data 24 noiembrie 2021 15:16:32
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");
int par[100005], dim[100005];
int cost;

vector<pair<int,pair<int,int>>> muchii;
vector<pair<int,int>> sol_m;

int find_node(int x)
{
    while(x!=par[x])
        x=par[x];
    return x;
}

void unite(int x,int y)
{
    int find_x=find_node(x);
    int find_y=find_node(y);
    if(dim[find_x]>=dim[find_y])
    {
        par[find_y]=find_x;
        dim[find_x]+=dim[find_y];
    }
    else
    {
        par[find_x]=find_y;
        dim[find_y]+=dim[find_x];
    }
}


void init(int n)
{
    for(int i=1; i<=n; ++i)
    {
        par[i]=i;
        dim[i]=1;
    }
}

int kruskall()
{
    int cost = 0;
    sort(muchii.begin(), muchii.end());
    for(auto muchie : muchii)
    {
        if(find_node(muchie.second.first) != find_node(muchie.second.second))
        {
            unite(muchie.second.first, muchie.second.second);
            cost += muchie.first;
            sol_m.push_back({muchie.second.first, muchie.second.second});
        }
    }
    return cost;
}

int main()
{
    int n,m;
    fin>>n>>m;
    init(n);
    for(int i=1; i<=m; i++)
    {
        int a,b,cost;
        fin>>a>>b>>cost;
        muchii.push_back({cost,{a,b}});
    }
    fout<<kruskall()<<'\n';
    fout<<sol_m.size()<<"\n";
    for(int i=0; i<sol_m.size(); i++)
        fout<<sol_m[i].first<<" "<<sol_m[i].second<<'\n';
    return 0;
}