Cod sursa(job #2328527)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 25 ianuarie 2019 20:59:40
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 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];
long long 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;
}

int doFather(int k) {
    if (k == father[k]) {
        return k;
    }
    father[k] = doFather(father[k]);;
    return father[k];
}

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

void solve() {
    for (int i = 0; k < maxNr; i++) {
        int x, y, cost;
        x = edges[i].x;
        y = edges[i].y;
        cost = edges[i].cost;
        if (doFather(x) != doFather[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;
}