Cod sursa(job #2043252)

Utilizator gabib97Gabriel Boroghina gabib97 Data 19 octombrie 2017 19:43:32
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
#define M 400005
#define N 200005

using namespace std;

int n, m, i, h[N], t[N];
vector<int> res;

struct Edge
{
	int x, y, c;
} edge[M];

int root(int n)
{
	int aux = n, T;
	while (t[n]) n = t[n];

	while (t[aux])
	{
		T = t[aux];
		t[aux] = n;
		aux = T;
	}

	return n;
}

int main()
{
	freopen ("apm.in", "r", stdin);
	freopen ("apm.out", "w", stdout);
	scanf("%i%i", &n, &m);
	int i;

	for (i = 1; i <= m; i++)
		scanf("%i%i%i", &edge[i].x, &edge[i].y, &edge[i].c);
	
	sort(edge + 1, edge + m + 1, [] (Edge a, Edge b) {return a.c < b.c;});
	
	int a, b, j = 0, cost = 0;
	for (i = 1; i < n; i++)
	{
		do
		{
			a = root(edge[++j].x);
			b = root(edge[j].y);
		} while (a == b);

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

	printf("%i\n%i\n", cost, res.size());
	for (int x: res)
		printf("%i %i\n", edge[x].x, edge[x].y);
	return 0;
}