Pagini recente » Cod sursa (job #2998336) | Cod sursa (job #924440) | Cod sursa (job #3232348) | Cod sursa (job #2663021) | Cod sursa (job #3271267)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("file.in");
ofstream fout("file.out");
struct edge {
int x,y,cost;
};
bool cmp(edge a, edge b) {
return a.cost < b.cost;
}
struct DSU {
vector<int> p, h;
DSU(int n) {
p.resize(n + 1);
h.resize(n + 1);
for (int i = 1 ; i <= n ; i ++) {
p[i] = i;
h[i] = 1;
}
}
int Find(int x) {
int r = x;
while (p[r] != r) {
r = p[r];
}
//actualizam toti copii la tatal lor este optimazare decat sa tot cauti din tata in fiu
int y = x;
while (y != r) {
int aux = p[y];
p[y] = r;
y = aux;
}
return r;
}
void Union(int x, int y) {
x = Find(x);
y = Find(y);
if (h[x] < h[y]) {
p[x] = y;
}else {
if (h[x] > h[y]) {
p[y] = x;
}else {
p[x] = y;
h[y] ++;
}
}
}
};
void Kruskal(int n, int m) {
DSU d(n);
vector<edge> e;
for (int i = 1 ; i <= m ; i ++) {
int x,y,c;
fin >> x >> y >> c;
e.push_back({x,y,c});
}
sort(e.begin(),e.end(),cmp);
int apm = 0 ;
vector<edge> sol;
for (auto i : e) {
if (d.Find(i.x) != d.Find(i.y)) {
d.Union(i.x,i.y);
apm += i.cost;
sol.push_back(i);
}
}
fout << apm << '\n' << sol.size() << '\n';
for (auto it : sol) {
fout << it.x << ' ' << it.y << '\n';
}
}
int main() {
int n,m;
fin >> n >> m;
Kruskal(n,m);
return 0;
}