Pagini recente » Cod sursa (job #832998) | Diferente pentru documentatie/tutorial-articole intre reviziile 13 si 12 | Cod sursa (job #1365534) | Cod sursa (job #514728) | Cod sursa (job #3320141)
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
struct Muchie {
int x;
int y;
int cost;
};
bool compare(Muchie &m1, Muchie &m2) {
return m1.cost < m2.cost;
}
int Find(int x, vector<int> &tata) {
while (tata[x] != 0) {
x = tata[x];
}
return x;
}
void Union(int x, int y, vector<int> &tata, vector<int> &h) {
x = Find(x, tata);
y=Find(y, tata);
if (h[x] < h[y]) {
tata[x]=y;
}
else if (h[x] > h[y]) {
tata[y]=x;
if (h[x] == h[y]) {
h[y]++;
}
}
}
int main() {
ifstream fin("grafpond.in");
int n, m, x, y, c, sol=0;
vector<Muchie> L, M;
fin>>n>>m;
for (int i=0; i< m; i++) {
fin>>x>>y>>c;
L.push_back(Muchie(x,y,c));
}
sort(L.begin(), L.end(), compare);
vector<int> tata(n+1, 0), h(n+1, 1);
for (const auto muchie : L) {
if (Find(muchie.x, tata) != Find(muchie.y, tata)) {
M.push_back(muchie);
sol+=muchie.cost;
Union(muchie.x, muchie.y, tata, h);
}
}
cout<<"Costul minim al arborelui partial este "<<sol<<"\n";
cout<<"Muchiile luate in considerare sunt:\n";
for (const auto m : M) {
cout<<m.x<<" "<<m.y<<" "<<m.cost<<"\n";
}
return 0;
}