Cod sursa(job #3243895)

Utilizator EricDimiericdc EricDimi Data 22 septembrie 2024 10:35:12
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
// Algoritmul lui Kruskal - O(M log M)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

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

const int MAX_N = 2e5, MAX_M = 4e5;
int n, m, t[MAX_N + 1], r[MAX_N + 1];

struct muchie
{
	int x, y;
	short cost;
} v[MAX_M + 1];

inline bool cmp(muchie a, muchie b)
{
	return a.cost < b.cost;
}

void Citire()
{
	f >> n >> m;

	for (int i = 1; i <= m; i++)
		f >> v[i].x >> v[i].y >> v[i].cost;

	f.close();
}

int Find(int x)
{
	if (t[x] == 0)
		return x;
	int k = Find(t[x]);
	t[x] = k;
	return k;
}

void Union(int x, int y)
{
    if (r[x] < r[y])
        t[x] = y;
    else
    {
        t[y] = x;
        if (r[x] == r[y])
            r[x]++;
    }
}

void Kruskal()
{
	sort(v + 1, v + m + 1, cmp);
	vector<pair<int, int>> sol;

	long long costMin = 0;

	for (int i = 1; i <= m; i++)
	{
		int rx = Find(v[i].x);
		int ry = Find(v[i].y);
		if (rx != ry)
		{
			Union(rx, ry);
			costMin += v[i].cost;
			sol.push_back({v[i].x, v[i].y});
		}
	}

	g << costMin << "\n" << sol.size() << "\n";
	for (auto edge : sol)
		g << edge.first << " " << edge.second << "\n";

	g.close();
}

int main()
{
	Citire();
	Kruskal();
	return 0;
}