Pagini recente » Cod sursa (job #2280488) | Cod sursa (job #1649684) | Cod sursa (job #2109405) | Cod sursa (job #1557353) | Cod sursa (job #3196490)
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
std::fstream fin("doc/grafpond.in");
// The struct data type
struct Path {
int fst; // First node
int scn; // Second node
int cost; // The cost of the path
};
int n, m, sum;
std::vector<Path> L;
std::vector<int> F;
std::vector<int> MST;
void MakeList(const int m) {
for (int i = 0; i < m; i++) {
// Reading the two nodes and the cost of a path
int x, y, c;
fin >> x >> y >> c;
L[i].fst = x;
L[i].scn = y;
L[i].cost = c;
}
}
// Sorting function for sort()
bool Sorting(const Path a, const Path b) { return a.cost < b.cost; }
void Initializing() {
for (int i = 0; i < n; i++) {
F[i] = i;
}
}
int FindK(int x) {
int r = x;
while (r != F[r]) {
r = F[r];
}
int y = x;
while (y != r) {
int t = F[y];
F[y] = r;
y = t;
}
return r;
}
int UnionK(int sum, int i) {
int x, y;
x = FindK(L[i].fst);
y = FindK(L[i].scn);
if (x != y) {
F[x] = y;
MST.push_back(i);
sum += L[i].cost;
}
return sum;
}
int main(int argc, char *argv[]) {
// Test if the file has succesfully open
if (!fin.is_open()) {
std::cout << "Error: Failed to open file." << std::endl;
exit(1);
}
// Reading the number of nodes and paths
fin >> n >> m;
L.resize(m);
MST.resize(m);
F.resize(n);
// Making the path list and sorting it
MakeList(m);
std::sort(L.begin(), L.end(), Sorting);
// Intializing the father vector
Initializing();
for (int i = 0; i < m; i++) {
sum = UnionK(sum, i);
}
std::cout << sum;
return 0;
}