Cod sursa(job #2807507)

Utilizator MihaiBirsanMihai Birsan MihaiBirsan Data 23 noiembrie 2021 21:10:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

#define Nmax 100010

ifstream fin("apm.in");
ofstream fout("apm.out");

int n,m,cost;
vector<pair<int,pair<int,int>>> muchii;
vector<pair<int,int>> subgr;
int par[Nmax];
int dim[Nmax];

//returneaza un ID pt componenta conexa a lui x
int findd(int x)
{
    while(x != par[x])
    {
        x = par[x];
    }
    return x;
}

//trage o muchie intre nodurile x si y(uneste componentele conexe a lui x si y)
void unite(int x, int y)
{
    x = findd(x);
    y = findd(y);
    if(dim[x] >= dim[y])
    {
        par[y] = x;
        dim[x] += dim[y];
    }
    else
    {
        par[x] = y;
        dim[y] += dim[x];
    }
}

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

void kruskal()
{

    sort(muchii.begin(), muchii.end());
    for(auto muchie: muchii)
    {
        if(findd(muchie.second.first) != findd(muchie.second.second))
        {
            unite(muchie.second.first, muchie.second.second);
            cost += muchie.first;
            subgr.push_back(make_pair(muchie.second.first, muchie.second.second));
        }
    }
}

int main()
{
    int x,y,c;
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        muchii.push_back(make_pair(c,make_pair(x,y)));
    }

    init();
    //sort(muchii.begin(), muchii.end());
    kruskal();
    fout << cost << "\n";
    fout << subgr.size() << "\n";

    for(int i = 0; i< subgr.size(); i++)
    {
        fout << subgr[i].first << ' ' << subgr[i].second;
        fout << "\n";

    }
    return 0;
}