Pagini recente » Cod sursa (job #1741035) | Cod sursa (job #1770836) | Cod sursa (job #1767404) | Cod sursa (job #2772598) | Cod sursa (job #1701415)
#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <deque>
using namespace std;
typedef pair<int,int> paer;
int top(int *graf, int x) {
int t = x;
while (graf[t]) {
int p = graf[graf[t]];
if (p) {
graf[t] = p;
}
t = graf[t];
}
if (t != x) {
graf[x] = t;
}
return t;
}
int main()
{
ifstream in("apm.in");
ofstream out("apm.out");
int n, m;
in>>n>>m;
set<pair<int, paer>> muchii;
set<pair<int, paer>>::iterator it;
int x, y, c, i;
for (i=0; i<m; i++) {
in>>x>>y>>c;
paer p = paer(x, y);
muchii.insert(pair<int, paer>(c, p));
}
int graf[n+1];
int h[n+1];
std::fill(graf, graf+n+1, 0);
std::fill(h, h+n+1, 0);
paer apm[n-1];
i = 0;
int suma = 0;
for (it = muchii.begin(); it != muchii.end(); it++) {
pair<int, paer> p = *it;
x = p.second.first;
y = p.second.second;
int t1 = top(graf, x), t2 = top(graf, y);
if (t1 != t2) {
suma += p.first;
if (h[t1] > h[t2]) {
graf[t2] = t1;
}
else {
graf[t1] = t2;
if (h[t1] == h[t2]) {
h[t2]++;
}
}
apm[i] = paer(p.second.first, p.second.second);
i++;
}
}
out<<suma<<endl;
out<<n-1<<endl;
for (i=0; i<n-1; i++) {
out<<apm[i].first<<" "<<apm[i].second<<endl;
}
in.close();
out.close();
return 0;
}