Pagini recente » Cod sursa (job #898970) | Cod sursa (job #578390) | Cod sursa (job #65891) | Cod sursa (job #2025368) | Cod sursa (job #3273544)
#include <bits/stdc++.h>
using namespace std;
int tata[100005], height[100005];
void reset(int n) {
for (int i = 1; i <= n; i++) {
tata[i] = i;
height[i] = 1;
}
}
int getRoot(int x) { // aproape O(1)
int root = x;
while (root != tata[root]) {
root = tata[root];
}
// compresia drumurilor
while (x != root) {
int tx = tata[x];
tata[x] = root;
x = tx;
}
return root;
}
void unite(int x, int y) { // aproape O(1)
x = getRoot(x);
y = getRoot(y);
if (height[x] < height[y]) {
tata[x] = y;
} else if (height[x] > height[y]) {
tata[y] = x;
} else { // egalitate
tata[y] = x;
height[x] += 1;
}
}
vector <pair <int, pair <int, int>>> edges;
vector <pair <int, pair <int, int>>> chosenEdges;
int main()
{
freopen("apm.in", "r", stdin);
freopen("apm.out", "w", stdout);
int n, m;
int costTotal = 0;
cin >> n >> m;
reset(n);
for (int i = 1; i <= m; i++) {
int x, y, cost;
cin >> x >> y >> cost;
edges.push_back(make_pair(cost, make_pair(x, y)));
}
sort(edges.begin(), edges.end());
for (auto edge: edges) {
int x = edge.second.first;
int y = edge.second.second;
int cost = edge.first;
if (getRoot(x) == getRoot(y)) continue; // daca se afla in aceeasi compo conexa, nu fac nimic
unite(x, y);
chosenEdges.push_back(make_pair(cost, make_pair(x, y)));
costTotal += cost;
}
cout << costTotal << '\n';
cout << chosenEdges.size() << '\n';
for (auto edge: chosenEdges) {
cout << edge.second.first << ' ' << edge.second.second << '\n';
}
return 0;
}