Pagini recente » Cod sursa (job #2963499) | Cod sursa (job #2016519) | Cod sursa (job #2393058) | Cod sursa (job #769758) | Cod sursa (job #3328503)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream cin("apm.in");
ofstream cout("apm.out");
struct muchie{
int x, y, cost;
};
vector <muchie> muchii;
vector <muchie> apcm;
int n, m, tt[101], sz[101], cost_total;
bool cmp (muchie a, muchie b){
return a.cost < b.cost;
}
int reprezentant (int x){
while (x != tt[x])
x = tt[x];
return x;
}
bool reunire (int i, int j){
int ri = reprezentant(i);
int rj = reprezentant(j);
if (ri != rj){
if (sz[ri] < sz[rj]){
tt[ri] = rj;
sz[rj] += sz[ri];
}
else{
tt[rj] = ri;
sz[ri] += sz[rj];
}
}
}
int main()
{
cin>>n>>m;
for (int i=1;i<=m;i++)
{
muchie edge;
cin>>edge.x>>edge.y>>edge.cost;
muchii.push_back(edge);
}
sort(muchii.begin(), muchii.end(), cmp);
for (int i=1;i<=n;i++)
tt[i] = i, sz[i] = 1;
for (auto edge : muchii)
{
int mx = edge.x;
int my = edge.y;
if (reprezentant(mx) != reprezentant(my)){
reunire(mx, my);
apcm.push_back(edge);
cost_total += edge.cost;
}
}
cout<<cost_total;
/*cout<<"Cost total: "<<cost_total<<'\n'<<"Muchiile:\n";
for (auto edge : apcm)
cout<<edge.x<<" "<<edge.y<<" "<<edge.cost<<'\n';*/
}
/*
Exemplu input:
9 14
1 3 -11
9 7 3
3 7 4
8 9 4
4 7 5
3 8 5
8 7 5
1 2 10
3 4 10
2 4 11
2 5 11
6 7 11
4 6 12
5 6 13
*/