Links: https://ac.nowcoder.com/acm/contest/992/J
Source: Cattle-off network
Title Description
Red and blue random born on apple tree apple Faerie, and now want to estimate their red line Sin CP coefficient, and decide whether to make them one pair of CP.
Gives the n nodes n-1 sides of the twig, the node numbered 1 to n, defined Distance (i, j) is the i and j from the tree.
CP refers to all coefficients red and blue at different locations i, j of Distance (i, j) sum.
即
∑i=1n−1∑j=i+1ndistance(i,j)\sum_{i=1}^{n-1}{\sum_{j=i+1}^{n}{distance(i,j)}}∑i=1n−1∑j=i+1ndistance(i,j)。
Seeking red and blue coefficients CP, for 10
. 9
+7 modulo.
Enter a description:
A first line integer n-(. 1 <n-<= 10
. 5
), indicates the number of tree nodes.
Then n-1 lines of three integers a, b, C (. 1 <= a, b <= n-), (0 <= C <= 10
. 9
), indicates the node a, b has a weight between value c side, (a
≠ \ NE = B).
Output Description:
Line an integer representing the coefficient CP 109
+7 result of modulo.
Example 1
Export
copy9
1 / * 2 . 3 tree dynamic programming: . 4 NUM [rt]: rt subtree how many nodes . 5 SUM [rt]: rt all child nodes of subtree to rt and distance . 6 ANS: all such points (i the [i, j] is not in the same straight line, j) and the distance . 7 // Sun [RT] then may be expressed as a sum of two points on the same straight line . 8 * / . 9 #include <bits / STDC ++. H> 10 the using namespace STD; . 11 const int N = 1E5 + . 7 ; 12 is const int MOD = + 1E9 . 7 ; 13 is typedef Long Long LL; 14 struct Node { 15 int id; 16 LL val; 17 }; 18 vector <node> g[N]; 19 LL num[N], sum[N]; 20 bool vis[N]; 21 int n; LL ans; 22 void dfs (int rt) { 23 vis[rt]=1; 24 for (int i=0;i<g[rt].size();i++) { 25 int nxt=g[rt][i].id; 26 if (!vis[nxt]) { 27 dfs(nxt); 28 LL d1=(sum[nxt]+num[nxt]*g[rt][i].val)%mod; 29 ans+=(d1*num[rt]%mod+sum[rt]*num[nxt]%mod)%mod; 30 num[rt]+=num[nxt]; 31 sum[rt]=(sum[rt]+d1)%mod; 32 } 33 } 34 num[rt]+=1; 35 //printf("rt: %d num: %lld sum: %lld ans: %lld\n",rt, num[rt], sum[rt], ans); 36 } 37 int main () 38 { 39 scanf("%d", &n); 40 for (int i=1;i<n;i++) { 41 int u, v; LL val; scanf("%d %d %lld", &u, &v, &val); 42 node tmp={v, val}; g[u].push_back(tmp); 43 tmp.id=u; g[v].push_back(tmp); 44 } 45 dfs(1); 46 for (int i=1;i<=n;i++) 47 ans=(ans+sum[i])%mod; 48 printf("%lld\n",ans); 49 return 0; 50 }