Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cmath>
- #include <iomanip>
- #include <tuple>
- #include <map>
- using namespace std;
- class DSU {
- public:
- vector<int> parent;
- vector<int> height;
- DSU(int n) {
- parent.resize(n);
- for (int i = 0; i < n; ++i) {
- parent[i] = i;
- }
- height.assign(n, 0);
- }
- int findRoot(int v) {
- if (v == parent[v]) {
- return v;
- }
- int ans = findRoot(parent[v]);
- parent[v] = ans;
- return ans;
- }
- void Union(int v1, int v2) {
- if (height[v1] >= height[v2]) {
- parent[v2] = v1;
- height[v1] = max(height[v1], height[v2] + 1);
- } else {
- parent[v1] = v2;
- height[v2] = max(height[v2], height[v1] + 1);
- }
- }
- };
- int main() {
- int n;
- cin >> n;
- vector<pair<double, pair<int, int>>> edges;
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < n; ++j) {
- int t;
- cin >> t;
- edges.push_back({t, {i, j}});
- }
- }
- DSU graph(n);
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < n; ++j) {
- int t;
- cin >> t;
- if (t && graph.findRoot(i) != graph.findRoot(j)){
- graph.Union(i, j);
- }
- }
- }
- sort(edges.begin(), edges.end());
- double ans = 0;
- for (auto [weight, coords]: edges) {
- if (graph.findRoot(coords.first) != graph.findRoot(coords.second)) {
- graph.Union(graph.findRoot(coords.first), graph.findRoot(coords.second));
- ans += weight;
- }
- }
- cout << ans;
- return 0;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement