Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code

#include <bits/stdc++.h>
using namespace std;

class UnionFind {
  public:
    int n;
    vector<int> parent;
    UnionFind(int n) {
        this->n = n;
        parent.resize(n);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }

  public:
    int find_set(int u) {
        if (parent[u] == u) {
            return u;
        }

        int root_x = find_set(parent[u]);
        parent[u] = root_x;
        return root_x;
    }

    void union_sets(int a, int b) {
        a = find_set(a);
        b = find_set(b);

        if (a != b) {
            parent[a] = b;
        }
    }
};

void solve() {
    int n, m;
    cin >> n >> m;

    UnionFind dsu(n);
    vector<pair<int, pair<int, int>>> edges;
    for (int i = 0; i < m; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        x--;
        y--;
        edges.push_back(make_pair(c, make_pair(x, y)));
    }

    sort(edges.begin(), edges.end());

    long long reward = 0;
    for (int i = 0; i < m; i++) {
        int reward_now = edges[i].first;
        int x = edges[i].second.first;
        int y = edges[i].second.second;

        if (dsu.find_set(x) != dsu.find_set(y)) {
            dsu.union_sets(x, y);
        } else {
            reward += max(0, reward_now);
        }
    }
    cout << reward << endl;
}

int main() {
    solve();
    return 0;
}