Cod sursa(job #2574677)

Utilizator maria.tantosMaria Iuliana Tantos maria.tantos Data 6 martie 2020 08:39:07
Problema Arbore partial de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, a, b, c, aux, s;

struct muchie
{
    int nod1;
    int nod2;
    int cost;
    bool ales;
};

bool cmp(muchie a, muchie b){
    return a.cost < b.cost;
}

int main()
{
    muchie mch[100];
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> a >> b >> c;
        mch[i].nod1 = a;
        mch[i].nod2 = b;
        mch[i].cost = c;
    }

    sort(mch+1, mch+m+1, cmp);

    int marcat[100] = {0};
    marcat[1] = 1;
    s = 0;
    bool gasit;
    for (int pas = 1; pas <= n-1; pas++)
    {
        gasit = 0;
        for(int i = 1; i <= m && !gasit; i++)
        {
            if ((marcat[mch[i].nod1] == 1 && marcat[mch[i].nod2] == 0) ||
                (marcat[mch[i].nod1] == 0 && marcat[mch[i].nod2] == 1))
            {
                s = s + mch[i].cost;
                marcat[mch[i].nod1] = 1;
                marcat[mch[i].nod2] = 1;
                gasit = 1;
                mch[i].ales = 1;
            }
        }
    }
    g << s << '\n';
    g<< n - 1 << '\n';
    for(int i = 1; i <= m; i++)
        if(mch[i].ales == 1)
            g << mch[i].nod1 << ' ' << mch[i].nod2 << '\n';
}