Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <vector>
- #include <algorithm>
- #include <numeric>
- using namespace std;
- std::vector<short> id;
- inline short root(short &i) {
- while (i != id[i]) {
- id[i] = id[id[i]];
- i = id[i];
- }
- return i;
- }
- int main() {
- std::ifstream fin("spantree2.in");
- std::ofstream fout("spantree2.out");
- std::ios_base::sync_with_stdio(false);
- fin.tie(nullptr);
- short n;
- short x, y;
- int w, m;
- std::vector<std::pair<int, std::pair<short, short>>> adj;
- int mst = 0;
- fin >>n>>m;
- n += 1;
- while (fin >>x >> y >> w)
- {
- adj.emplace_back(w, std::make_pair(x, y));
- }
- id.resize(n);
- std::iota(id.begin(), id.end(), 0);
- stable_sort(adj.begin(), adj.end());
- int parent1, parent2;
- std::vector<int> sz(n, 1);
- for (const auto &edge : adj) {
- short src = edge.second.first;
- short dest = edge.second.second;
- if (root(src) != root(dest)) {
- mst += edge.first;
- if (src == dest)
- continue;
- parent1 = root(src);
- parent2 = root(dest);
- if (parent1 == parent2)
- continue;
- if (sz[parent1] < sz[parent2])
- std::swap(parent1, parent2);
- id[parent2] = parent1;
- sz[parent1] += sz[parent2];
- }
- }
- fout << mst;
- fin.close();
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement