Cod sursa(job #998180)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 16 septembrie 2013 00:02:30
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <tuple>
using namespace std;

const string file = "apm";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f;


int N, M;
vector<pair<int, pair<int, int> > > edges;
vector<pair<int, int> > selected;


vector<int> grad;
vector<int> tata;

int MinCost;

int Find(int x)
{
	int a = x;
	while(tata[x] != 0)
	{
		x = tata[x];
	}

	while(tata[a] != 0)
	{
		int t = tata[a];
		tata[a] = x;
		a = t;
	}

	return x;
}

void Union(int x, int y)
{
	if(grad[x] > grad[y])
		swap(x, y);

	grad[y] += grad[x];
	tata[x] = y;
}



int main()
{
	fstream fin(infile.c_str(), ios::in);
	fin >> N >> M;
	edges.reserve(M);
	selected.reserve(N - 1);

	grad.resize( N + 1, 1);
	tata.resize( N + 1);

	for(int i = 0; i < M; i++)
	{
		int x, y, c;
		fin >> x >> y >> c;
		edges.push_back(make_pair(c, make_pair(x, y)));
	}

	fin.close();

	less<pair<int, pair<int, int> > > comp;
	sort(edges.begin(), edges.end(), comp);

	for(vector<pair<int, pair<int, int> > > ::iterator itr = edges.begin();
		itr != edges.end();
		itr++)
	{
		int a = Find(itr->second.first);
		int b = Find(itr->second.second);
		if( a != b)
		{
			Union(a, b);
			MinCost += itr->first;
			selected.push_back(itr->second);
		}
	}

	fstream fout(outfile.c_str(), ios::out);
	fout << MinCost << "\n";
	fout << selected.size() << "\n";
	for(vector<pair<int, int> > ::iterator itr = selected.begin();
		itr != selected.end();
		itr++)
	{
		fout << itr->first << " " << itr ->second << "\n";
	}
	fout.close();
}