Pagini recente » Cod sursa (job #1658033) | Cod sursa (job #1032636) | Cod sursa (job #117907) | Cod sursa (job #183147) | Cod sursa (job #2071642)
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct Node{
int first;
int second;
int weight;
};
void init(int &nodes, vector< int > &Parent){
for (int i = 0; i <= nodes; i++)
Parent.push_back(i);
}
int Root(int n, vector< int > &Parent){
if (Parent[n] == n)
return n;
Parent[n] = Root(Parent[n], Parent);
return Parent[n];
}
void Union(int x, int y, vector< int > &Parent){
Parent[Root(x, Parent)] = Root(y, Parent);
}
bool cmp(Node a, Node b){
return a.weight < b.weight;
}
int main(){
int nodes, edges;
fin >> nodes >> edges;
vector< Node > Graph;
vector< int > Parent;
vector< Node > MST;
init(nodes, Parent);
for (int i = 0; i < edges; i++){
int x, y, w;
Node aux;
fin >> x >> y >> w;
aux.first = x;
aux.second = y;
aux.weight = w;
Graph.push_back(aux);
}
sort(Graph.begin(), Graph.end(), cmp);
int ans = 0;
for (int i = 0; i < edges; i++){
if (Root(Graph[i].first, Parent) != Root(Graph[i].second, Parent)){
ans += Graph[i].weight;
Union(Graph[i].first, Graph[i].second, Parent);
MST.push_back(Graph[i]);
}
}
//cout << "The minimal cost is :\n";
fout << ans << " " << nodes - 1 << endl;
//cout << "And is composed of the following edges :\n";
for (int i = 0; i < MST.size(); i++)
fout << MST[i].first << " " << MST[i].second << endl;
return 0;
}