Cod sursa(job #2021098)

Utilizator mihailarminia1234Arminia Mihail mihailarminia1234 Data 12 septembrie 2017 17:52:51
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

struct muchie
{
        int nodX, nodY, cost;
        muchie(int x, int y, int c)
        {
                nodX = x;
                nodY = y;
                cost = c;
        }
        muchie() {}
};

struct el
{
        int x, y;
        el *next;
};

el *head, *p, *q;
muchie v[400005];
int n, m, arbore[200005], costTotal;
bool ok = false;

void Adaugare(int x, int y)
{
        if(head == NULL)
        {
                p = new el;
                p -> x = x;
                p -> y = y;
                p -> next = NULL;
                head = p;
        }
        else
        {
                q = new el;
                q -> x = x;
                q -> y = y;
                q -> next = NULL;
                p -> next = q;
                p = q;
        }
}

void Citire()
{
        f >> n >> m;
        for(int i = 1; i <= m; ++i)
        {
                int x, y, cost;
                f >> x >> y >> cost;
                v[i] = muchie(x, y, cost);
        }
}

void init_arb()
{
        for(int i = 1; i <= n; ++i) arbore[i] = i;
}

void Kruskal()
{
        int pas = 1, i = 0, a, b;
        while(pas < n)
        {
                ++i;
                a = arbore[v[i].nodX];
                b = arbore[v[i].nodY];
                if(arbore[a] != arbore[b])
                {
                        ++pas;
                        costTotal += v[i].cost;
                        Adaugare(v[i].nodX, v[i].nodY);
                        for(int j = 1; j <= n; ++j)
                                if(arbore[j] == a) arbore[j] = b;
                }
        }
}

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

void Afisare()
{
        g << costTotal << '\n' << n - 1 << '\n';
        for(p = head; p != NULL; p = p -> next)
                g << p -> x << " " << p -> y << '\n';
}

int main()
{
        Citire();
        init_arb();
        sort(v + 1, v + m + 1, cmp);
        Kruskal();
        Afisare();
        return 0;
}