Cod sursa(job #2401389)

Utilizator JustAndyNiculae Andrei JustAndy Data 9 aprilie 2019 17:45:10
Problema Arbore partial de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

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

struct muchie{
    int x,y,cost;
}v[101],t[101];

int n,m,s[101],ct,cont;

void citire()
{
    in>>n>>m;
    for(int i=1;i<=m;i++)
    {
        in>>v[i].x>>v[i].y>>v[i].cost;
    }
}

void kruskal()
{
    int a,b;
    for(int i=1;i<=n;i++)
        s[i] = i;
    for(int i=1;i<=m;i++)
    {
        a=s[v[i].x];
        b=s[v[i].y];
        if(a!=b)
        {
            ct+=v[i].cost;
            cont++;
            t[cont].x = v[i].x;
            t[cont].y = v[i].y;
            for(int j=1;j<=n;j++)
            {
                if(s[j] == b)
                    s[j] = a;
            }
        }
    }
}

bool cmp(muchie st, muchie dr)
{
    return st.cost<dr.cost;
}

int main()
{
    citire();
    sort(v+1,v+m+1,cmp);
    kruskal();
    out<<ct<<'\n'<<cont<<'\n';
    for(int i=1;i<=cont;i++)
    {
        out<<t[i].x<<' '<<t[i].y<<'\n';
    }
    return 0;
}