Cod sursa(job #2115874)

Utilizator Tyler_BMNIon Robert Gabriel Tyler_BMN Data 27 ianuarie 2018 11:06:23
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#include <vector>
#include <algorithm>

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

int n, m;
const int MAXN = 200002;
const int MAXM = 400004;
int parent[MAXN];
int cost = 0;
struct edge {
	int x, y, cost;
}graph[MAXM];

int root(int x) {
	if (parent[x] == 0)
		return x;
	
	return parent[x] = root(parent[x]);
}

vector<int> sol;

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

int main() {
	fin >> n >> m;
	for (int i = 0; i < m; i++) {
		fin >> graph[i].x >> graph[i].y >> graph[i].cost;
	}

	sort(graph, graph + m, cmp);
	for (int i = 0; i < m; i++) {
		if (root(graph[i].x) != root(graph[i].y)) {
			parent[root(graph[i].x)] = root(graph[i].y);
			sol.push_back(i);
			cost += graph[i].cost;
		}
	}
	fout << cost << "\n" << sol.size() << "\n";
	for (int i : sol) {
		fout << graph[i].x << " " << graph[i].y << "\n";
	}
}