Cod sursa(job #1704882)

Utilizator Bijoux12Andreea Gae Bijoux12 Data 19 mai 2016 15:31:21
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <vector>
#include <utility>
#include <fstream>
#include <algorithm>

using namespace std;

vector<pair<pair<int,int>,int > > graph;
vector <pair <int, int> > graph_final;
int n, m, costTotal;

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

class DisjointDataSet 
{
	vector<int> rang;
	vector<int> parent;
public:
	DisjointDataSet(int);
	int findRoot(int);
	void link(int, int);
	void unionSets(int, int);
};

DisjointDataSet::DisjointDataSet(int n)
{
	rang.resize(n + 1, 0);
	parent.resize(n + 1);
	for (int i = 0; i < n + 1; i++)
		parent[i] = i;
}


int DisjointDataSet::findRoot(int x) 
{
	int i, aux;

	for (i = x; parent[i] != i; i = parent[i])
	{

	}
	while (parent[x] != x) 
	{
		aux = parent[x];
		parent[x] = i;
		x = aux;
		rang[i]--;
	}
	return i;
}

void DisjointDataSet::link(int x, int y) 
{
	if (rang[x] < rang[y]) 
		parent[x] = y;
	else
	{
		if (rang[x] > rang[y])
			parent[y] = x;
		else 
		{
			parent[x] = y;
			rang[y]++;
		}
	}
}

void DisjointDataSet::unionSets(int x, int y)
{
	link(findRoot(x), findRoot(y));
}

bool cmp(const pair<pair<int,int>,int >  &a, const pair<pair<int,int>,int > &b)
{
	return (a.second < b.second);
}

void kruskal()
{
	sort(graph.begin(), graph.end(), cmp);
	DisjointDataSet d(n);
	int x, y, c;
	for (int i = 0; i < graph.size(); i++)
	{
		x = graph[i].first.first;
		y = graph[i].first.second;
		c = graph[i].second;
		if (d.findRoot(x) != d.findRoot(y)) 
		{
			graph_final.push_back(make_pair(x, y));
			d.unionSets(x, y);
			costTotal += c;
		}
	}
}

int main() 
{
	f >> n >> m;
	for (int i = 0; i < m; i++)
	{
		int nod1, nod2, cost;
		f >> nod1 >> nod2 >> cost;
		graph.push_back(make_pair(make_pair(nod1, nod2), cost));
	}
	kruskal();
	g << costTotal << endl<< graph_final.size() << endl;
	for (auto it = graph_final.begin(); it != graph_final.end(); it++) 
	{
		g << it->first << " " << it->second << endl;
	}
	f.close();
	g.close();
	return 0;
}