Cod sursa(job #2325830)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 22 ianuarie 2019 22:50:23
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#define MAXM 400010
#define MAXN 200010

using namespace std;

struct element {
    int x, y, cost;
    bool operator<(const element &other) const {
        return (cost < other.cost);
    }
}edges[MAXM], solution[MAXN];

int n, m, maxNr, k = 0, father[MAXN], height[MAXN], solCost = 0;

void initialize() {
    for (int i = 1; i <= n; i++) {
        father[i] = i;
        height[i] = 1;
    }
}

void readInput() {
    ifstream fin("apm.in");
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, cost;
        fin >> x >> y >> cost;
        edges[i] = {x, y, cost};
    }
    maxNr = n - 1;
}

void reunite(int x, int y) {
    father[x] = father[y];
    if (height[x] == height[y])
        height[x] = height[y] = height[x] + 1;
}

void doFather(int k, int &value) {
    if (k == father[k]) {
        value = k;
        return;
    }
    doFather(father[k], value);
    father[k] = value;
}

void solve() {
    for (int i = 0; k < maxNr; i++) {
        int x, y, cost, value;
        x = edges[i].x;
        y = edges[i].y;
        cost = edges[i].cost;
        doFather(x, value);
        doFather(y, value);
        if (father[x] != father[y]) {
            solCost += cost;
            reunite(x, y);
            solution[k++] = {x, y, cost};
        }
    }
}

void printSolution() {
    ofstream fout("apm.out");
    fout << solCost << "\n" << maxNr << "\n";
    for (int i = 0; i < maxNr; i++)
        fout << solution[i].x << " " << solution[i].y << "\n";
}

int main() {
    readInput();
    sort(edges, edges + m);
    initialize();
    solve();
    printSolution();
    return 0;
}