Cod sursa(job #2500504)

Utilizator mircearoataMircea Roata Palade mircearoata Data 28 noiembrie 2019 09:13:52
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

int t[200005];
int h[200005];

int findSet(int x)
{
	while (x != t[x])
		x = t[x];
	return x;
}

void uniteSet(int x, int y)
{
	x = findSet(x);
	y = findSet(y);
	if (x == y)
		return;
	if (h[x] == h[y])
	{
		t[y] = x;
		h[x]++;
	}
	else if (h[x] < h[y])
		t[x] = y;
	else
		t[y] = x;
}

struct edge {
	int x, y, c;
};

vector<edge> G, ansEdges;

int n, m, ans;

int main()
{
	in >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		t[i] = i;
		h[i] = 1;
	}
	for (int i = 1; i <= m; i++)
	{
		int x, y, c;
		in >> x >> y >> c;
		G.push_back({ x, y, c });
	}
	sort(G.begin(), G.end(), [](const edge& l, const edge& r) { return l.c < r.c; });
	for (const edge& e : G)
	{
		if (findSet(e.x) != findSet(e.y))
		{
			uniteSet(e.x, e.y);
			ans += e.c;
			ansEdges.push_back(e);
		}
	}
	out << ans << '\n';
	out << ansEdges.size() << '\n';
	for (const edge& e : ansEdges)
		out << e.x << ' ' << e.y << '\n';
}