Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include".\template\headers.hpp"
- //#define MULTI_TASKCASE
- using namespace abb;
- using namespace output;
- using namespace rit;
- using namespace wit;
- inline void init() {
- }
- struct edge {
- int a, b; ll v;
- };
- bool operator<(edge a, edge b) {
- return a.v < b.v;
- };
- inline void solve() {
- int n, m;
- while (cin >> n >> m) {
- V<edge> v(m);
- for (auto& i : v)
- cin >> i.a >> i.b >> i.v;
- sort(v.begin(), v.end());
- V<int> d(n);
- iota(d.begin(), d.end(), 0);
- F<int(int)> find = [&](int x) {
- return x == d[x] ? x : (d[x] = find(d[x]));
- };
- auto merge = [&](int a, int b) {
- d[find(a)] = find(b);
- };
- ll ans = 0;
- for (auto& i : v)
- if (find(i.a) != find(i.b))
- ans += i.v, merge(i.a, i.b);
- for (int i = 1; i < n; i++)
- if (find(0) != find(i))
- goto no_result;
- cout << ans << endl;
- continue;
- no_result :
- cout << -1 << endl;
- }
- }
- main() {
- ios::sync_with_stdio(false);
- init();
- int t = 1;
- #ifdef MULTI_TASKCASE
- cin >> t; cin.ignore();
- #endif
- while (t--) solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement