Cod sursa(job #2042916)

Utilizator Y.MalmsteenB.P.M. Y.Malmsteen Data 19 octombrie 2017 13:47:44
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
const int INF = 1 << 25;

struct muchie
{
    int i, j, c;
};

int n, m, cost;
muchie M[400001];
short int CC[200001];
//bool S[400001];
short int mapm[200000];

void citire()
{
    f >> n >> m;
    for(int i = 1; i <= m; i++)
        f >> M[i].i >> M[i].j >> M[i].c;
}

void afis()
{
    g << cost << '\n' << n - 1 << '\n';
    //for(int i = 1; i <= m; i++)
    //if(S[i]) g << M[i].i << ' ' << M[i].j << '\n';
    for(int i = 1; i < n; i++)
        g << M[mapm[i]].i << ' ' << M[mapm[i]].j << '\n';
}

bool comp(const muchie &a, const muchie &b)
{
    return a.c < b.c;
}

void Kruskal()
{
    sort(M + 1, M + m + 1, comp);
    for(int i = 1; i <= n; i++)
        CC[i] = i;
    int poz = 0, napm = 0;
    for(int l = 1; l < n; l++)
    {
        int k = poz;
        do
        {
            k++;
        }
        while(CC[M[k].i] == CC[M[k].j]);
        //S[k] = 1;
        mapm[++napm] = k;
        cost += M[k].c;
        poz = k;
        int ccj = CC[M[k].j];
        for(int i = 1; i <= n; i++)
            if(CC[i] == ccj)
                CC[i] = CC[M[k].i];
    }
}

int main()
{
    citire();
    Kruskal();
    afis();
    return 0;
}