Cod sursa(job #2575728)

Utilizator maria.tantosMaria Iuliana Tantos maria.tantos Data 6 martie 2020 15:11:10
Problema Economie Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("graf.in");
ofstream g("graf.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[400002];
    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[200002];
    for(int i = 1; i <= n; i++) marcat[i] = 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';
    return 0;
}