Cod sursa(job #2779089)

Utilizator rares89_Dumitriu Rares rares89_ Data 2 octombrie 2021 17:48:50
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <algorithm>

using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

int n, m, k; // k = muchiile lui P
int total; // cost final
int t[400005]; // vect de tati

struct Muchie {
	int x, y, c;
} v[400005], P[400005]; // P -> muchiile apm

void Union(int a, int b) {
    t[a] = t[b];
}

int Find(int nod) {
    while(t[nod] != nod) {
    	nod = t[nod];
    }
    return nod;
}

bool cmp(Muchie A, Muchie B) {
    return A.c < B.c;
}

int main() {
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
    	fin >> v[i].x >> v[i].y >> v[i].c;
    }
    fin.close();
    sort(v + 1, v + m + 1, cmp);
    for(int i = 1; i <= n; i++) {
    	t[i] = i;
    }
    for(int i = 1; i <= m; i++) {
        int nod1 = Find(v[i].x);
        int nod2 = Find(v[i].y);
        if(nod1 != nod2) {
        	Union(nod1, nod2);
            P[++k] = v[i];
            total += v[i].c;
        }
    }
    fout << total << "\n";
    fout << n - 1 << "\n";
    for(int i = 1; i < n; i++) {
        fout << P[i].y << " " << P[i].x << "\n";
    }
	return 0;
}