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
| #include <bits/stdc++.h> using namespace std; struct Node { int v, w; Node(int v, int w) : v(v), w(w) {} }; const int MAXN = 600010; const int mod = 100000007; vector<Node> edge[MAXN]; inline void addEdge(int u, int v, int w) { edge[u].push_back(Node(v, w)); edge[v].push_back(Node(u, w)); } char ch; bool iosig; template<class T> inline void read(T &x) { iosig = 0, x = 0; do { ch = getchar(); if (ch == '-') iosig = 1; } while (!isdigit(ch)); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ '0'), ch = getchar(); } int size[MAXN], vis[MAXN], dep[MAXN]; typedef long long ll; long long ans; void dfs(int u) { size[u] = 1, vis[u] = true; for (int i = 0; i < edge[u].size(); i++) { Node *x = &edge[u][i]; if (!vis[x->v]) { dep[x->v] = dep[u] + 1; dfs(x->v); size[u] += size[x->v]; } } } int n; int main() { read(n); for (int i = 1, u, v, w; i < n; i++) { read(u), read(v), read(w); addEdge(u, v, w); } dep[1] = 1; dfs(1); for (int u = 1; u <= n; u++) { for (int i = 0; i < edge[u].size(); i++) { if (dep[u] + 1 == dep[edge[u][i].v]) ans += (ll)size[edge[u][i].v] * (n - size[edge[u][i].v]) % mod * edge[u][i].w % mod; ans %= mod; } } cout << 2 * ans % mod; return 0; }
|