Cod sursa(job #2865949)

Utilizator ardutgamerAndrei Bancila ardutgamer Data 9 martie 2022 11:41:35
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

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

const int NMAX = 200005;

struct Edge
{
	int x, y, cost;
	void print() {fout << x << ' ' << y << '\n';}
	Edge(int x, int y, int cost) { this->x = x; this->y = y; this->cost = cost; }
	bool operator<(const Edge& other) const {
		return cost < other.cost;
	}
};

vector<Edge>v;
vector<Edge>sol;
int n, m;

int t[NMAX], h[NMAX];

void read()
{
	fin >> n >> m;
	while (m--)
	{
		int x, y, cost;
		fin >> x >> y >> cost;
		v.push_back(Edge(x, y, cost));
	}
	for (int i = 1; i <= n; i++)
		t[i] = i, h[i] = 1;
}

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[y] = x;
	else
		t[x] = y;
}

void print(vector<Edge>& v)
{
	fout << v.size() << '\n';
	for (Edge &e : v)
		e.print();
}

void solve()
{
	sort(v.begin(), v.end());
	int nr = 0;
	int cost = 0;
	for (Edge &e : v)
	{
		int tx = findSet(e.x);
		int ty = findSet(e.y);
		if (tx == ty) continue;
		nr++;
		cost += e.cost;
		uniteSet(tx, ty);
		sol.push_back(e);
		if (nr >= n - 1) break;
	}
	fout << cost << '\n';
	print(sol);
}

int main()
{
	read();
	solve();
	return 0;
}