Pagini recente » Cod sursa (job #1979791) | Arhiva de probleme | Cod sursa (job #1248839) | Cod sursa (job #1918484) | Cod sursa (job #1704029)
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
pair<int, pair < int , int > > *Graf;
int *t, *h;
int n, m;
int cautare_tata(int *t, int nod){
while (t[nod] != 0) {
nod = t[nod];
}
return nod;
}
int main(){
int i, k;
int x, y, ct;
f>>n>>m;
Graf = new pair < int, pair < int , int > > [m + 1];
t = new int [n + 1];
h = new int [n + 1];
for(i=1; i<=m; i++){
f>>x>>y>>ct;
Graf[i].first = ct;
Graf[i].second.first = x;
Graf[i].second.second = y;
}
sort(Graf, Graf + m);
for(i=1; i<=n; i++){
t[i] = 0;
h[i] = 0;
}
k = 1;
i = 1;
ct = 0;
while (k <= n - 1) {
int nod1, nod2;
nod1 = cautare_tata(t, Graf[i].second.first);
nod2 = cautare_tata(t, Graf[i].second.second);
if(nod1 != nod2){
ct = ct + Graf[i].first;
k = k + 1;
if(h[nod1] > h[nod2]){
t[nod2] = nod1;
}else{
t[nod1] = nod2;
if(h[nod1] == h[nod2]){
h[nod2] = h[nod2] + 1;
}
}
}
i = i + 1;
}
g<<"cost : "<<ct;
return 0;
}