Cod sursa(job #2462279)

Utilizator gabib97Gabriel Boroghina gabib97 Data 26 septembrie 2019 23:00:21
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
#define N 200005

using namespace std;

struct edge {
	int x, y, c;
};
vector<edge> edges;
vector<int> res;
int t[N], h[N], cost;

int root(int n) {
	while (t[n]) n = t[n];
	return n;
}

int main() {
	freopen ("apm.in", "r", stdin);
	freopen ("apm.out", "w", stdout);
	
	int n, m, x, y, c;
	scanf("%i%i", &n, &m);
	for (int i = 1; i <= m; i++) {
		scanf("%i%i%i", &x, &y, &c);
		edges.push_back((edge){x, y, c});
	}
	sort(edges.begin(), edges.end(), [](const edge &a, const edge &b) {return a.c < b.c;});

	int a, b, j = -1;
	for (int i = 1; i < n; i++) {
		do {
			a = root(edges[++j].x);
			b = root(edges[j].y);
		} while (a == b);

		cost += edges[j].c;
		res.push_back(j);
		if (h[a] > h[b])
			t[b] = a;
		else if (h[b] > h[a])
			t[a] = b;
		else {
			t[a] = b;
			h[b]++;
		}
	}

	printf("%i\n%i\n", cost, n - 1);
	for (int e : res)
		printf("%i %i\n", edges[e].x, edges[e].y);

	return 0;
}