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 79 80 81 82
| #include <bits/stdc++.h> using namespace std; const int iol = 1024 * 1024; char buf[iol], *ioh, *iot, ioc; inline char read() { if (ioh == iot) { iot = (ioh = buf) + fread(buf, 1, iol, stdin); if (ioh == iot) return -1; } return *ioh++; } template<class T> inline void read(T& x) { for (ioc = read(); !isdigit(ioc); ioc = read()); x = 0; for (; isdigit(ioc); ioc = read()) x = (x << 1) + (x << 3) + (ioc ^ '0'); } struct DisjointSet { int *rank, *father, size; inline int get(int x) { register int p = x, i; while (p != father[p]) p = father[p]; while (x != p) i = father[x], father[x] = p, x = i; return p; } inline void put(int x, int y) { x = get(x), y = get(y); if (rank[x] > rank[y]) father[y] = x; else { father[x] = y; if (rank[x] == rank[y]) rank[y]++; } } inline void init(int x) { rank[x] = 0, father[x] = x; } DisjointSet(int n) : rank(new int[n + 1]), father(new int[n + 1]), size(n + 1) { for (register int i = 1; i <= n; i++) father[i] = i; } } *s; struct Node { int u, v, w; Node(int u, int v, int w) : u(u), v(v), w(w) {} Node() {} inline bool operator < (const Node &n) const { return w > n.w; } }; Node edge[100010]; int tot; inline void addEdge(int u, int v, int w) { edge[++tot] = Node(u, v, w); } typedef long long ll; const int mod = 1e9; int n, m, cnt[100010]; ll sum, ans; int main() { read(n), read(m); for (int i = 0, u, v, w; i < m; i++) { read(u), read(v), read(w); addEdge(u, v, w); sum += w; if (sum >= mod) sum -= mod; } sort(edge + 1, edge + tot + 1); s = new DisjointSet(n); fill(cnt + 1, cnt + n + 1, 1); for (int i = 1; i <= tot; ++i) { register int fa1 = s->get(edge[i].u), fa2 = s->get(edge[i].v); if (fa1 != fa2) { ans = (ans + (ll)cnt[fa1] * (ll)cnt[fa2] * sum) % (ll)mod; s->father[fa2] = fa1; cnt[fa1] += cnt[fa2]; } sum -= (ll)edge[i].w; } cout << (ans % (ll)mod + (ll)mod) % (ll)mod; return 0; }
|