1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <string> #include <vector>
#define DEBUG(x) std::cerr << #x << " = " << x << std::endl; #define forall(G,u) for (int i_ = 0, __for_siz__ = (int) G[u].size(); i_ < __for_siz__; ++i_)
using std::cin; using std::cout; using std::endl;
inline int read() { int s = 0, x = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') x = -x; ch = getchar(); } while (isdigit(ch)) { s = s * 10 + ch - '0'; ch = getchar(); } return s * x; }
const int MAXN = 200000 + 10;
struct REdge { int u, v, w; REdge(int _u = 0, int _v = 0, int _w = 0) { u = _u; v = _v; w = _w; } bool operator < (const REdge &th) const { return w > th.w; } } es[MAXN];
struct DSU { int u[MAXN]; bool circ[MAXN];
DSU() { memset(u, 0, sizeof u); memset(circ, 0, sizeof circ); } int Find(int x) { return !u[x] ? x : u[x] = Find(u[x]); } bool Merge(int x, int y) { x = Find(x), y = Find(y); if (x == y) { if (!circ[x]) { circ[x] = true; return true; } else return false; } if (circ[x] && circ[y]) return false; u[x] = y; circ[y] |= circ[x]; return true; } } U;
int n, m;
long long int Kruskal() { std::sort(es + 1, es + 1 + m); int cnt = 0; long long int ans = 0; for (int i = 1; i <= m; ++i) { if (U.Merge(es[i].u, es[i].v)) { ans += es[i].w; ++cnt; } if (cnt == n) break; } return ans; }
int main() { n = read(); m = read(); for (int i = 1; i <= m; ++i) { int u = read(); int v = read(); int w = read(); es[i] = REdge(u, v, w); } printf("%lld\n", Kruskal()); return 0; }
|