We are given a tree with n nodes. Each edge has a value (clamminess) x and a color (0=red,1=black). For each unordered pair of nodes (u, v), consider the unique simple path between them. Let the path have R red edges and B black edges. If |R - B| <= 2, then we include this path and compute the product of the clamminess of edges on this path. Then the jelliness is the product over all such valid paths (unordered pairs) of those products. Since product of products can be expressed as product of each edge raised to some exponent (how many valid paths include that edge). The answer is that product modulo MOD=1e9+7.
So essentially we need for each edge e, its exponent = number of unordered node pairs (u,v) such that the path between u and v includes e and the condition |R - B| <= 2 holds for that path. Then answer = ∏_e (x_e)^{exponent} mod MOD.
The tree size up to 1e5, so we need to compute exponent efficiently.
Observation: Condition on number of red and black edges on the path. Let each edge have color: red (0) or black (1). For a path, let total number of edges = L, and difference d = R - B? Actually R + B = L, and condition is |R - B| <= 2. Equivalent to |2R - L| <= 2 or |2B - L| <= 2. Also can be expressed: R and B must be within 2 of each other.
We can treat each node? Possibly use centroid decomposition or DP to count pairs of nodes satisfying condition. But we need per-edge contributions. Another way: total product over valid paths can be computed via inclusion exponent from number of valid paths that pass through each edge. But computing per edge contributions maybe doable using counting of pairs in subtrees with constraints on red/black counts.
Consider rooting tree arbitrarily. For each edge e connecting parent p and child c (with child's subtree). Then number of paths that include e = (size of subtree rooted at c) * (n - size_subtree). Among those, only those where the condition holds on the whole path between u and v. However, the condition depends on the whole path, not just the contributions from the subtree. But we can perhaps define for each node, we compute number of nodes in its subtree with certain (red, black) counts from the root. Then for any two nodes u and v, their path counts can be obtained as combination of root-to-u and root-to-v minus twice root-to-lca. But the condition depends on red and black counts along the path.
Specifically, pick a root (say node 1). For any two nodes u, v, let a = (r_u, b_u) be number of red/black edges on path from root to u. Similarly (r_v, b_v). Let w = LCA(u, v). Let (r_w, b_w) for root to w. Then path from u to v: red count = r_u + r_v - 2r_w, black count = b_u + b_v - 2b_w. Condition: |(r_u + r_v - 2r_w) - (b_u + b_v - 2b_w)| <= 2. Equivalent to |(r_u - b_u) + (r_v - b_v) - 2(r_w - b_w)| <= 2.
Let diff(x) = r_x - b_x. Then condition: |diff(u) + diff(v) - 2*diff(w)| <= 2.
Note that diff can be negative. So the condition is about the sum of diffs of u and v minus twice the diff of LCA.
This is reminiscent of counting pairs with constraints involving LCA. Could use centroid decomposition: When we decompose, for each centroid, we consider paths passing through the centroid. For each such path, we can compute the diff from centroid to node (with sign depending on direction). Then for two nodes in different subtrees of the centroid, the overall path's diff = diff_centroid_to_u + diff_centroid_to_v? Actually careful: For a path (u, v) that passes through centroid C (where C is the LCA in the rooted tree if we root at centroid? But if we treat paths that go through centroid, we can consider centroid as the highest point. For any two nodes u and v from different subtrees of C, the path u-v goes through C, and the total red/black counts on path = (red from u to C) + (red from C to v). Similarly black. So diff_total = diff(u to C) + diff(C to v). If we define for each node its diff from centroid along the unique path, taking direction into account: for a node x in a subtree, let d(x) = diff from centroid to x (i.e., red_count - black_count on that path). Then for two nodes u and v from different subtrees, diff_total = d(u) + d(v). However, note: The centroid to each node path might be oriented away from centroid. That's fine. Also the centroid itself is included? The edges from centroid to its children. So condition: |d(u) + d(v)| <= 2. Also we need to consider pairs where one node is centroid itself? In centroid decomposition we can handle by adding dummy node with diff 0. But careful: Paths where centroid is an endpoint: then path diff = d(u) for the other endpoint. Condition: |d(u)| <= 2 (since other endpoint centroid has diff 0). So we can treat centroid as a node with d=0.
Thus, using centroid decomposition, we can count number of unordered pairs (u, v) such that path goes through the centroid (i.e., centroid is on the path, not necessarily LCA but as long as the path includes centroid). Actually in centroid decomposition we typically consider paths that go through the centroid, counting pairs from different subtrees, and also include centroid as one endpoint. That covers all distinct unordered pairs exactly once because each path has a unique centroid in the decomposition tree? Actually centroid decomposition recursively partitions; when processing a centroid, we consider all paths that go through that centroid and have all other nodes from different subtrees (i.e., the centroid is the highest point of the path in the decomposition sense). But we must ensure each pair (u,v) is counted exactly once, typically the path is counted when we process the first centroid (in the decomposition recursion) that lies on the path; that centroid is the one that is the nearest to the root of the decomposition? Actually standard approach: For counting pairs with some condition, we decompose tree, and for each centroid, we consider all nodes in its current component, and count pairs from different subtrees that satisfy condition. Then we remove centroid and recursively process each subtree. This ensures each unordered pair of nodes is counted exactly once, because for any pair, there is a unique centroid in the recursion that is the first (highest) centroid on which the two nodes lie in different subtrees (i.e., the centroid of the component that contains both nodes before separation). So it's valid.
Thus we can count total number of valid paths (i.e., number of unordered pairs (u,v) satisfying condition) via centroid decomposition. However, we need not just count, but for each edge compute exponent. The exponent is number of valid paths that include that edge. That's more fine-grained. But we can possibly compute for each edge the number of valid paths that pass through it using similar centroid decomposition but with contributions assigned to edges? Alternatively, we could compute for each edge its contribution by considering pairs of nodes where the path includes that edge. That can be expressed as: For edge e separating subtree S (size s) and complement (n-s), the number of valid paths crossing e is the number of pairs (u in S, v not in S) such that the path condition holds. So if we can compute, for a given bipartition (subset S and complement), the number of valid pairs across the cut, we could do that for each edge individually. But that would be O(n^2) if done naively.
Thus we need a more clever way: The product over valid paths can be computed as product over edges of x_e^{cnt_e}. cnt_e can be computed by counting valid paths crossing that edge. So we need an algorithm that computes cnt_e for all edges efficiently.
We can possibly use rerooting DP, and count for each edge the number of valid paths that go through it in O(n * something). Since condition is based on red-black difference, which is additive along paths, maybe we can treat each node's diff from root and use data structures to count pairs crossing an edge? But when we cut an edge, we need to count pairs (u in subtree, v outside) such that |diff(u) + diff(v) - 2*diff(lca(u,v))| <= 2. However, if we root tree arbitrarily and consider edge between parent p and child c, then lca for any u in subtree c and v outside will be either p (if v is outside subtree c) or maybe something else if v is also in subtree c? Actually if u in subtree(c) and v outside, then lca(u,v) is some node on the path from p to root. Specifically, LCA is the first common ancestor; since u is under c and v is not in c's subtree, the LCA will be on the path from p to root, possibly p itself if v is not also under some other child of p? Let's analyze: Tree rooted at some root R. For edge p->c (c child of p). Consider any node u in subtree of c. Any node v not in that subtree. The LCA of u and v is either p (if v is not in the subtree of c but could be in other subtree of p or above p) OR it could be some ancestor higher than p if v is in a different subtree that also is not under p? Actually if v is outside subtree(c), there are two cases:
- v is in a different subtree of p (i.e., v is in subtree of another child of p). Then LCA(u,v) = p.
- v is outside the entire subtree of p (i.e., not in subtree(p)). Then LCA(u,v) is some ancestor of p, possibly the root. So it could be above p.
Thus lca is not fixed; it depends.
So cutting edge p-c, the condition for pair (u in subtree(c), v outside) depends on lca which might be p or higher. This complexity suggests that per-edge counting is not straightforward.
Alternative approach: Since product over paths can be expressed as ∏ over edges x_e^{#valid paths containing e}, we can compute the exponent modulo (MOD-1) maybe? But MOD is prime, exponent can be large, but we can compute exponent modulo (MOD-1) due to Fermat? Actually for exponent modulo MOD-1, if we compute product via exponentiation, we can compute exponent modulo MOD-1 because a^{k mod (MOD-1)} = a^k mod MOD for prime MOD (Fermat) only if a is not multiple of MOD? Actually a^(phi(MOD)) ≡ 1 mod MOD when gcd(a, MOD)=1. Here MOD=1e9+7 prime, and edge weights x are between 1 and 1e9+6, so x may be divisible by MOD? 1e9+7 is prime, so only multiple is 0 mod MOD? Actually x could be MOD? But constraints: x ≤ 10^9 + 6, so max is 1e9+6 < MOD, so x is not 0 mod MOD, thus gcd(x, MOD)=1. So we can reduce exponent modulo MOD-1 (since by Fermat's little theorem, x^{MOD-1} ≡ 1 mod MOD). So we can compute exponent mod (MOD-1). That might help if we compute total product via inclusion but exponent may be huge, but we just need modulo 1e9+6.
But we still need to compute exponent efficiently.
Perhaps there is a simpler solution: The condition |R-B| <= 2 is very loose. Maybe we can compute the product of all paths' products? Could be expressed as (∏ over all paths of product of edges) = ∏_e x_e^{(# of paths that include e)}. So it's the same problem.
Another thought: Since the condition depends only on difference between red and black counts, we might assign each node a weight w = diff from root. Then the condition for a path between u and v becomes | (w_u - w_{lca}) + (w_v - w_{lca}) |? Actually diff(u) = w_u (where w_u = r_u - b_u from root). Then path diff = w_u + w_v - 2 w_{lca}. So condition: | w_u + w_v - 2 w_{lca} | <= 2.
Now, if we could count for each edge e, the number of pairs (u,v) whose path includes e, with this condition. Perhaps we can compute contributions for each possible "difference" value at nodes and use some data structure while traversing.
Consider a rooted tree. For each node, we can maintain data about its subtree. For edge (p, c), we want count of pairs (u in subtree(c), v outside) that satisfy condition. Suppose we precompute for each node the distribution of w values in its subtree. Then for edge p-c, we have set A = subtree(c) (size s), set B = rest of nodes (size n-s). We need number of pairs (a∈A, b∈B) such that | w_a + w_b - 2 w_{lca(a,b)} | <= 2. But lca depends on where b is relative to p. For b in B, if b is not in subtree(c), lca(a,b) is either p if b is in some other subtree of p, or some ancestor above p if b is outside p's subtree. That's messy.
Another idea: Use centroid decomposition but not just for counting pairs; we can also compute contributions of edges to the exponent. In centroid decomposition, when processing a centroid C, we consider all paths that pass through C. For each such path, we can increment a counter on each edge along that path? That would be too heavy.
But we might compute for each edge e, its contribution to the total number of valid paths as: for each valid unordered pair (u,v), each edge on the path gets +1. So total sum over edges of cnt_e = total_valid_paths * (average path length) but that's not helpful.
Perhaps we can compute the answer directly as product over all valid paths of product of edges, but using generating functions? For each path, product of edge weights. If we could compute the product of all such path products without per-edge exponents, maybe we can compute via DP merging subtrees? For example, for each node, compute the product of all valid paths within its subtree, and then combine with parent using something like "tree DP with convolution on differences". But the product of products across all pairs is tricky.
Alternatively, we can consider that exponent for edge e = number of valid paths that include e. In a tree, number of paths that include e = s_e * (n - s_e) where s_e is size of one side. But we need to restrict to those paths that also satisfy the color condition. So we need to count, among those s_e*(n-s_e) pairs, how many satisfy condition.
Thus for each edge e, we need count of pairs (u in side A, v in side B) such that condition holds. If we can quickly compute, for a given bipartition of the tree (a connected subtree A and its complement B), the number of valid pairs across the cut, then we can compute for each edge.
But we have n-1 edges, so we need an O(n polylog n) algorithm.
Maybe we can precompute for each node the distribution of diff values, and then for each edge we can compute something like: For each possible diff value in side A, we need to count nodes in side B with diff values satisfying condition, but with lca factor. However, if we root the tree at some node, and consider edge p-c, side A is subtree(c), side B is rest. For nodes a in A, their w_a = diff from root. For nodes b in B, the path from a to b: w_a + w_b - 2 w_{lca(a,b)}. The lca(a,b) is the lowest common ancestor of a and b. Since a is in subtree(c), and b is outside that subtree, lca can be p or above. If b is in a different subtree of p, then lca = p. If b is outside subtree(p), then lca is some ancestor of p. So the term -2 w_{lca} depends on where b is.
Maybe we can restructure the counting by considering the path condition as sum of two "signed" differences. In centroid decomposition approach, for centroid C, we treat paths that pass through C. For such paths, condition simplifies to |d(u)+d(v)| <= 2 (where d is diff from C). Moreover, each such path will be counted exactly once. For each path, we could determine all edges on that path and increment counts. But maybe we can compute the total product of edge weights over all valid paths by, during centroid processing, multiplying contributions from combinations of nodes. That is, we can compute the answer directly as the product over all valid unordered pairs (u,v) of product_{e in path(u,v)} x_e. We can compute this product via divide and conquer: For each centroid, consider all paths that go through it, and multiply together the products of edge weights for each valid pair. But how to combine efficiently? For each pair (u,v) from different subtrees of centroid, the product of edge weights on path = (product of edges from centroid to u) * (product of edges from centroid to v). Because the path from u to v goes u->...->C->...->v. So product = P(u) * P(v), where P(x) denotes product of edge weights on the path from centroid to x (including the edge adjacent to centroid? careful: If centroid is node C, then path from u to v includes edges from u to C and from C to v. So product = (prod on u-C) * (prod on C-v). This holds if we define P(u) as product of weights on edges from C to u (including all edges along that path). Then indeed product = P(u)*P(v). Additionally, for pairs where one endpoint is C itself, we can treat P(C)=1, and the product = P(u). So the product for each valid pair is product of the two "path products" from centroid.
Thus, if we can, for each centroid, compute the product over all unordered pairs (u,v) from different subtrees (including centroid) that satisfy |d(u)+d(v)| <= 2 of P(u)*P(v). Moreover, we need to consider also pairs within the same subtree? Those will be counted when processing deeper centroids in recursion.
So overall answer = product over all centroids (of the contributions from paths that go through that centroid). Because each unordered pair (u,v) is counted exactly once, at the centroid where it is separated.
Now, the answer for the whole tree can be computed recursively: For a given component, we pick a centroid C. We compute contributions from all paths that go through C (i.e., pairs of nodes from different child subtrees or C itself). Then remove C and recursively process each remaining component (subtree after removing C). This is typical.
So we need to compute, for a centroid C, given several groups (subtrees) of nodes (each group corresponds to a child of C in the current component), each node has two attributes: d (diff in red-black count from C) and P (product of edge weights from C to that node). For each unordered pair of nodes (including C) from different groups, we need to multiply P(u)*P(v) into answer if |d(u)+d(v)| <= 2.
But also we need to consider pairs where one node is C and another node from any group: then condition |d(v)+0| <= 2, i.e., |d(v)| <= 2, and contribution = P(v). (since product = P(v)*1). So we can treat C as a special node with d=0, P=1, and belonging to its own group (or just handle separately).
Now, the problem reduces to: Given multiple lists of items (nodes), each item with integer d and value P (mod MOD). Compute product over all unordered pairs (i, j) from distinct lists (including maybe also C) such that |d_i + d_j| <= 2 of P_i * P_j. Multiply all these contributions together (mod MOD).
But careful: The overall answer is the product over all valid paths of product of edge weights. In centroid decomposition, we are multiplying contributions from each such pair. This multiplication is commutative and associative, so we can indeed multiply across centroids. However, we must ensure that each path is counted exactly once, and we multiply exactly the product of edge weights of that path. In centroid decomposition, when we consider paths through centroid, we are multiplying P(u)*P(v). But note that P(u) includes edge weights from centroid to u; P(v) includes from centroid to v. So their product equals the product over the whole path. Good.
Now, we need to compute product of many P_i * P_j. Since multiplication is over many terms, we can compute exponent sums: For each centroid, the contribution = ∏{pairs i,j, distinct groups, condition} (P_i * P_j) = (∏{pairs} P_i) * (∏{pairs} P_j) = (∏{pairs} P_i) * (∏_{pairs} P_j) which is symmetric. Actually each term P_i appears in pairs with all eligible j from other groups. So the total exponent of P_i is the number of eligible j from other groups that satisfy condition with i. So if we compute for each node i, the number of eligible partners in other groups, then contribution = ∏_i P_i^{cnt_i} where cnt_i is number of such partners. However, note that each pair contributes both P_i and P_j, so P_i gets multiplied for each eligible j. So yes.
Thus contribution = ∏i P_i^{cnt_i}, where i runs over all nodes in the component (including centroid? careful for centroid's own product). For centroid (if we treat as node with P=1), exponent doesn't matter. So we could compute product as ∏{i in component (excluding centroid? but including nodes in subtrees)} P_i^{cnt_i}. But cnt_i depends on d_i and the distribution of other groups.
But we also need to ensure that when we multiply contributions from different centroids, we are not double counting edges? Actually each path is accounted exactly once, so the overall product is correct.
Now, we need to compute, for each centroid processing, the product contribution efficiently. Since total number of nodes across all centroid levels is O(n log n) (each node appears in O(log n) centroids), we could afford O(size of component * log size) maybe, but we must be careful about total complexity O(n log^2 n) or O(n log n). The condition |d_i + d_j| <= 2 is a small range because d_i and d_j are integers but they could be as large as O(n) (since diff can be up to n). However, we are only interested in sums in range [-2,2]. So for each node i, we need to count how many nodes j from other groups have d_j in the range [-2 - d_i, 2 - d_i]. That's a range of length at most 5. So we can use frequency maps for d values across groups.
But we also need to compute product contributions, not just counts. We need to compute the product of P_i raised to the count of eligible partners. However, that would require exponentiation per node, but we can combine by exponent summation: final answer = ∏_centroids ∏_i P_i^{cnt_i}.
We can compute, for each centroid, the overall factor = ∏{i} P_i^{cnt_i}. Since cnt_i may be large (up to O(n)), we can compute exponent modulo MOD-1. But we need the product modulo MOD. We can compute exponent accumulators for each node? But node appears in many centroid levels; we need to multiply its P_i contribution each time it is considered (when it's in a component with a centroid). Actually each node will be considered many times (once per centroid on the path from node to root of centroid tree). But in the decomposition, when a node is not the centroid of a component, it belongs to some subtrees that will be processed with centroids deeper. However, each pair (u,v) is counted only once, at the level where the centroid is the first that separates them. In that processing, both u and v are present in the component and we consider them at that centroid. After that, u and v are in different subtrees and will not be paired again. So each node appears in the processing of many centroids (as part of the component), but its pairing with others only happens at the centroid where they are separated. That's typical: In centroid decomposition, each node is considered in O(log n) levels (as part of components), but its pairing with others occurs only when it is in the same component as the centroid and the other node is from a different subtree. So for each node i, over the whole recursion, it will be paired with other nodes exactly once (when they are separated). So the total sum of cnt_i over all centroid processings for a given node i equals the number of valid paths that have i as one endpoint? Wait careful: For a node i, when it is paired with node j, that pair is counted in the centroid step where they are separated. In that step, both i and j are in the component, and they are in different child subtrees of the centroid. Then the contribution multiplies P_i and P_j. So i gets its P_i multiplied in that pair's contribution. So each node i's P_i factor accumulates exponent equal to number of valid partners j (unordered pairs where i is one endpoint) that are paired with i at the centroid where they are separated. However, note that for a path (i,j), both endpoints i and j will each get a factor of their own P_i and P_j in the product. So the overall answer is ∏{i} P_i^{deg_i}, where deg_i is the number of valid paths where i is one endpoint? But careful: For each unordered pair (i,j), the contribution is P_i * P_j, so in the product, P_i appears once for that pair. So indeed, exponent for node i (i.e., the factor contributed by node i across all centroid processings) is exactly the number of valid unordered pairs (i,j) (with i != j) such that the path condition holds. But that's not exactly the number of valid paths that include i? Actually if we sum over all unordered pairs (i,j), each pair contributes factor P_i * P_j. So overall product = ∏_i P_i^{num_pairs_with_i}. So the exponent of P_i equals the number of valid paths where i is one endpoint. But P_i is the product of edge weights from some centroid to i, which varies per centroid step. Wait, P_i is defined relative to the centroid of the current component. In different centroid steps, the same node i may have different P_i values, because P_i is the product of edge weights on the path from the current centroid to i. So we cannot define a global P_i. The factorization we attempted earlier: contribution = ∏_i P_i^{cnt_i} per centroid. But the P_i in each centroid step is different. So we cannot combine across centroids as a simple product over nodes.
Thus we need to compute the overall product directly by iterating over centroids and multiplying contributions per pair, but we need to do it efficiently.
One approach: For each centroid step, we need to compute:
Prod = ∏{pairs (u,v) from different subtrees, |d_u + d_v| <= 2} (P_u * P_v) * (also pairs with centroid: ∏{u, |d_u| <= 2} P_u).
This is equivalent to:
Prod = (∏_{u} P_u^{cnt_u}) where cnt_u = number of eligible partners in other groups (including centroid? but centroid as partner counts as 1 if condition holds). So per centroid we could compute each node's exponent. But the number of nodes across all centroids is O(n log n), and for each node we need to compute cnt_u quickly.
We could compute, for each centroid, the total product by iterating over groups and using frequency maps. Since condition on d sum is small range, we can maintain a global frequency map (for nodes already processed from other groups) of d values, but also we need the product of P values for each d? Actually for counting partners for each node, we need number of nodes from other groups with d in a certain range. But for exponent accumulation, we need to multiply P_u by itself for each such partner. So if we have a frequency count for each d value across processed groups, we can compute for each node u: cnt_u = total number of nodes from other groups with d in [L, R]. Then we need to multiply answer by P_u^{cnt_u}. However, doing this per node could be O(n log n) nodes total, which is okay (1e5 * log 1e5 ~ 1.7e6). But exponentiation per node (fast pow) would add log MOD (which is about 30), total maybe 5e7 operations, might be okay in C++? But we also need to compute the product of P_u for all nodes? Actually we need to raise P_u to cnt_u and multiply into answer. That's exponentiation per node, but we can maybe combine: For each distinct d value, we can compute the sum of cnt for nodes with that d? But cnt depends on node's d and also the distribution of other groups. However, if we process groups one by one, and for each node in the current group, we compute cnt based on the already accumulated global map (from previous groups) and also from groups not yet processed? But we need pairs from different groups, so when processing groups sequentially, we can update answer using pairs between current group and already processed groups. That is typical for centroid counting problems. For each centroid, we can maintain a global map (like a frequency table) that accumulates counts of nodes from groups processed so far. For each new group, for each node in that group, we query the map for number of compatible nodes (based on d) and then multiply answer by P_u raised to that count. Then after processing all nodes in the group, we add the nodes of this group to the map (so they can pair with subsequent groups). Also we need to handle pairs with the centroid separately: we can simply treat centroid as a node with d=0, P=1, and add it to the map initially? But careful: centroid should pair with nodes from all groups, and condition is |d_u|<=2. So we could initialize the map with the centroid (d=0, count 1, product? but for pairs, we multiply by P_u for each such partner. Since centroid's P=1, its contribution is just 1. So we can just handle centroid pairs by: for each node u in all groups, if |d_u|<=2, then multiply answer by P_u (since centroid pairs with u contributes P_u). That is equivalent to adding a dummy node with d=0 to the map initially. However, we must be careful not to double count: When we process groups, we need to consider pairs between nodes from different groups, and also between centroid and nodes. Using the map approach: We can start with an empty map. Then for each group, before adding its nodes, we query the map for each node u in the group to compute contributions with already processed groups (including possibly centroid if we added it). But we also need to account for pairs between centroid and nodes. If we add centroid to the map initially (with d=0, count 1, and product factor maybe 1), then when we process a node u from group, if |d_u + 0| <=2, the query will return count 1, and we multiply answer by P_u (since centroid's P=1). That's correct. But careful: The centroid itself is not in any group, but we can treat it as a separate group processed first. So we can add centroid to map initially. Also we need to ensure that we don't count pairs within the same group; the map only contains nodes from previous groups, so that's fine. Also note: For pairs between two nodes in the same group, they will be counted later when processing that group? Actually in the map method, we process groups one by one, and before adding a group to the map, we compute contributions with previously processed groups. So pairs within the same group are not counted because they are not in different groups. That's correct because such pairs do not have the centroid on the path? Wait, are pairs within the same group supposed to be counted at this centroid? For a pair of nodes both in the same child subtree of centroid, the path between them does not pass through the centroid (unless centroid is on the path? In a tree, if both nodes are in the same child's subtree, the unique path between them stays within that subtree and does not go through the centroid because centroid is at the root of the component, but the path might go through centroid only if centroid lies on the path. If centroid is connected to that child, and both nodes are in that child's subtree, the path between them will be entirely within that subtree (since the subtree is connected via the child, and centroid is outside). Actually consider centroid C connected to child A. For two nodes u, v in the subtree of A, the path from u to v goes up to the LCA which is somewhere inside that subtree; it may or may not go through C. If both are in the same child subtree, the path does not include C because C is not in that subtree; it is outside. The path goes from u up to the child A (maybe further up) but to reach v, it never goes to C because C is the parent of A, but the path from u to v might go up to A then maybe up to C? Actually if the subtree of A is attached to C via edge (C-A). For any two nodes in that subtree, their LCA is some node in that subtree. The path from u to v will be entirely within that subtree; it will not include C because the only connection to C is through A, but if both are below A, the path between them does not need to go up to C unless one is on one side of A and the other is on the other? But A is the root of that subtree; if the LCA is A itself, then the path goes through A, but does it include C? The path from u to v: u -> ... -> A -> ... -> v. That goes through A but not necessarily C because C is above A. Since both u and v are in subtree rooted at A, the path stays within that subtree; the highest point is A (or above A if the LCA is above A? But there is no node above A within the subtree; the parent of A is C, which is outside the subtree. So the LCA cannot be C because C is not in the subtree (by definition, the subtree is the set of nodes reachable from A without passing through C). So LCA is in the subtree and thus path does not include C. Therefore, pairs within the same child subtree are not counted at this centroid; they will be handled later when that subtree is processed recursively as its own centroid decomposition. So indeed we only count pairs from different groups (or with centroid). Good.
Now, we need to efficiently compute for each node u in a group, the number of already processed nodes (including centroid) with d value in [L,R] where L = -2 - d_u, R = 2 - d_u. That's a constant range length 5. So if we maintain a map from d to count (number of nodes with that d), we can query the sum over d in that small range. Since d values can be large (up to O(n)), we can use a hash map (unordered_map) or we can compress coordinates per centroid. But the total number of nodes across all groups for a centroid is size of component, and we do this for each node. That would be O(total nodes in component) operations plus small range queries if we use a map with O(1) average. However, we also need to compute exponentiation: answer = answer * (P_u)^{cnt} mod MOD for each node u. So that would be O(n log n) exponentiations, which might be heavy but possibly acceptable? n=1e5, log n ~ 17, total nodes processed across centroids is O(n log n) ~ 1.7e6. For each node we need to compute pow(P_u, cnt) mod MOD. pow is O(log exponent) but exponent cnt can be up to n, so log exponent is up to ~30. 1.7e6 * 30 = 51e6 operations, which is okay in C++ if optimized. But we also need to build the groups: for each centroid, we need to traverse each subtree to compute d and P for nodes. That's O(size of component) per centroid, total O(n log n) as well.
Thus, the algorithm seems plausible:
- Build tree adjacency with edges: each edge has weight x and color c (0/1). We'll need to compute for each node, when we root at a centroid temporarily, the values d (red-black diff) and P (product of weights) from centroid.
But note: d is red count minus black count on path from centroid to node. Since the tree is unrooted, for each centroid we need to compute these by DFS through the component, ignoring the centroid (which is removed). We also need to handle that edges have colors: d is sum of (+1 for red? or -1? Actually we need diff = R - B. So we can assign each edge a delta: +1 for red, -1 for black? Or the opposite? Actually diff = (#red) - (#black). So if edge is red, diff contribution +1; if black, -1. Then d(node) = sum of delta along path from centroid to node.
Also P = product of x modulo MOD.
We need to compute d and P for each node in the component.
Now for each centroid step:
- We have centroid C.
- Initialize an empty frequency map (e.g., unordered_map<int, int> cntMap) that will store counts of d values from already processed groups. Also we might need to store product of P values? Actually for counting pairs we only need number of nodes with a given d. Because for each node u, we need count of partners. That's fine. But wait: For the contribution, we multiply P_u for each partner. That's accomplished by raising P_u to power cnt. So we don't need the actual P values of partners, only their count. So map from d to count suffices.
- First, add centroid to map: d_centroid = 0, count=1. (But do we need to consider centroid's own product? Not needed.)
- Then for each child subtree of C (in the current component), we do:
- Run DFS to collect all nodes in that subtree (within the component, i.e., not crossing removed centroid) and compute for each node: d, P (product from centroid). Also we need to store list of (d, P) for nodes in this group.
- For each node in this group, compute L = -2 - d, R = 2 - d. Then query map to get total count of nodes (from previous groups plus centroid) with d' in [L,R]. Let cnt = that count. Multiply answer by pow_mod(P, cnt) (mod MOD). (Note: P is product of edge weights from centroid to node, mod MOD.)
- After processing all nodes in this group (i.e., after using them to compute contributions with earlier groups), we then add the nodes of this group to the map: for each node, increment cntMap[d] by 1. (We may also need to store product? No, because later groups will only need counts.)
- After processing all groups, we have accounted for all pairs (u,v) where u and v are from different groups or one is centroid.
Now, what about pairs between nodes from the same group? They will be handled in deeper recursion when that group becomes its own component.
But we must also consider that the product P for each node is computed relative to centroid C. That's correct for the path product because for path between u (in group i) and v (in group j) that goes through C, the product of edges on the path is P(u) * P(v). So raising P(u) to cnt (where cnt is number of compatible v from other groups) and similarly later when processing v from its group? Actually careful: In our method, when we process group i, we multiply answer by P_u^{cnt} for each u in group i, where cnt is number of compatible nodes from previous groups (including centroid). But then later when we process group j (which comes after group i), we will multiply answer by P_v^{cnt'} for each v in group j, where cnt' includes nodes from groups processed before j, which includes group i and centroid. So the pair (u from group i, v from group j) will contribute P_u * P_v. In our method, it appears as: when processing u (in group i), we multiply by P_u^{1} because cnt includes v? Actually if cnt includes v, then we multiply answer by P_u for that pair? Let's examine: Suppose we have groups processed in order: first centroid (added to map), then group A, then group B. For a node u in group A, when we process it, the map contains centroid and maybe earlier groups (none besides centroid). So u's cnt includes centroid if compatible, and not any from group B because B not yet added. So u does not get exponent from nodes in B. Then when processing group B, we multiply for each v in B: P_v^{cnt} where cnt includes nodes from centroid and group A. So v's cnt includes u (if compatible). So we multiply by P_v for that pair. The pair (u,v) contributes P_u * P_v, but we only multiplied P_v, not P_u. We missed multiplying P_u for that pair! Because u's processing did not see v, and v's processing multiplied P_v. So we are missing the factor P_u. That suggests we need to multiply both ends: For each unordered pair (u,v) from different groups, the contribution is P_u * P_v. So both P_u and P_v must be multiplied into the answer exactly once. Our method of raising P_u to the number of compatible v's (when u is processed) would indeed include P_u for each partner v, but only if we process u after v? Let's think:
- If we add nodes to map after processing a group, then when processing a later group, nodes from earlier groups are in the map, so later nodes multiply by their own P to the count of earlier nodes. That gives factor P_later for each pair.
- But earlier nodes do not get factor from later nodes. So each pair is accounted only once, with factor being P of the node from the later group, not both. That is not correct because the product should include both P_u and P_v.
We need to incorporate both P_u and P_v. There are two symmetrical ways:
- For each pair, we need to multiply both P_u and P_v. So we could, when processing a node, multiply by P_u^{cnt} where cnt is number of compatible partners from earlier groups. That yields factor P_u per pair where u is the later node. But we still need to multiply by P_v for that same pair where v is the earlier node. To also include the earlier node's factor, we could also multiply by something like the product of P of earlier nodes to the power of number of later nodes? But that's not captured in our per-node exponent method if we only multiply by P_u for later nodes.
Alternative: Instead of raising P_u to cnt, we could multiply answer by (P_u)^{cnt} * (product of P of earlier nodes)??? That seems messy.
Better: When we process a node u from a new group, we could compute the sum of contributions for all pairs (v,u) where v is from earlier groups. The contribution for pair (v,u) is P_v * P_u. So we need to multiply answer by (P_u)^{cnt} * (product of P_v over all compatible v)?? Actually the product over all such pairs is ∏{v compatible} (P_v * P_u) = (∏{v compatible} P_v) * (P_u^{cnt}). So for each node u, we need to multiply by both P_u^{cnt} and the product of P_v of all compatible v from earlier groups. So we need to know not only the count of compatible v but also the product of their P values.
Thus we need to maintain for each d value not only the count but also the product of P values for nodes with that d (from earlier groups). Then for each new node u, we can compute:
- total_count = sum_{d' in [L,R]} cnt[d']
- total_product = ∏{d' in [L,R]} ( ∏{v with d'} P_v ) i.e., the product of all P_v of compatible nodes from earlier groups.
Then contribution from all pairs (v,u) where v is earlier and u is current node is: (total_product) * (P_u^{total_count}). Because each pair contributes P_v * P_u, and the product over v is (∏ P_v) * (P_u^{#v}) = (total_product) * (P_u^{total_count}).
We also need to multiply by the product of pairs between u and centroid? That's included if centroid is in earlier groups.
Similarly, after processing all nodes in a group, we need to update the data structure to include these nodes for future groups. So we need to maintain, for each d, two values: count[d] and prod[d] = product of P values for nodes with that d. When adding a node with d and P, we do:
count[d] += 1
prod[d] = prod[d] * P % MOD
But careful: The product of P values can be huge, but we keep modulo MOD.
Now, for each node u, we need to compute:
total_count = sum_{d' = L to R} count[d']
total_prod = product_{d'=L to R} prod[d'] (mod MOD)
Then contribution = total_prod * pow_mod(P_u, total_count) % MOD.
We multiply answer by contribution.
But also we must consider that total_prod is the product of all P_v for v in earlier groups that are compatible. However, note that for each v, we will eventually also multiply by its P_v when it gets paired with later nodes? Actually each unordered pair (v,u) will be considered exactly once: when processing the later node u, we multiply by P_v * P_u. At that time, P_v has already been stored in prod[d'], and we multiply it into answer. Later, when we process further nodes w, we will multiply by P_v * P_w as well, which includes P_v again. So P_v may be multiplied many times, once for each later compatible partner. That's correct because each pair including v contributes factor P_v. So we need to multiply by P_v each time it appears in a pair. So storing prod[d'] and multiplying it each time we pair with a new node is correct: that gives factor P_v for each compatible pair involving v as earlier node.
But caution: When we multiply total_prod (which is product of P_v over compatible earlier nodes) by P_u^{total_count}, we are effectively adding factor P_v for each v and P_u for each v. However, what about the case where there are multiple nodes with the same d? total_prod is product of all P_v for v with d in range. So when we multiply answer by total_prod, that includes each P_v once per each new node u? Actually for a given new node u, we multiply total_prod (which includes P_v for all compatible v) and then also P_u^{count}. So the factor contributed by this multiplication is ∏{v compat} (P_v) * (P_u)^{#v}. That indeed adds factor P_v once per pair (v,u). So after processing all groups, each unordered pair (v,u) where v appears in an earlier group and u in a later group will have contributed exactly one factor P_v and one factor P_u. So the overall product will include ∏{pairs} (P_v * P_u) as desired. And pairs with centroid (v=centroid) will be included as centroid has P=1, so its factor is 1; but centroid's count adds to total_count, and its prod factor is 1, so contribution works.
Thus we need to maintain for each centroid a data structure that can, given d, quickly retrieve sum of counts and product of P values over a small range of d (range length 5). Since d values can be large (like -1e5 to 1e5), but the range is small, we can use a hash map to store count and prod keyed by d. For each node, we iterate over the 5 possible d' values that satisfy d' in [L,R]. Since range length is at most 5, we can just loop over those integers and query the hash map. That would be O(1) per node, albeit with small constant. So for each node, we do:
L = -2 - d
R = 2 - d
total_count = 0
total_prod = 1
For t = L to R:
if map contains t:
total_count += cnt[t]
total_prod = total_prod * prod[t] % MOD
ans = ans * total_prod % MOD
ans = ans * pow_mod(P_u, total_count) % MOD
But careful: When total_count is 0, total_prod should be 1 (since empty product). Also, pow_mod(P_u, 0)=1.
After processing all nodes in the current group, we then insert each node into the map: for each node, update cnt[d]++, prod[d] = prod[d] * P_u % MOD.
Now, we also need to handle the case of centroid itself as a group: We'll start with map containing centroid: d=0, cnt[0]=1, prod[0]=1 (since P=1). Then for each group (child subtree), we process as above.
Also note: The product P for nodes is computed as the product of edge weights along path from centroid to node. Since edges have weights up to 1e9+6, we store them modulo MOD.
Now, what about the path product for pairs where both nodes are centroid? There's only one centroid, no pair. So fine.
Now, after processing centroid C, we remove it from the tree (mark as deleted) and recursively process each connected component (each child subtree) separately.
Edge Cases: Need to consider that the product of P values may become huge; we use modulo MOD.
Now, we must ensure that the answer for the whole tree is computed correctly. However, we need to verify that the decomposition method indeed multiplies the correct product for each unordered pair exactly once.
Consider any unordered pair (u,v) of distinct nodes. In the centroid decomposition, there is a unique centroid C that lies on the path between u and v and is the first centroid encountered in the recursion where u and v are in different child subtrees (or one of them is the centroid). At that step, both u and v are present in the component, and they belong to different groups (or one is centroid). The pair (u,v) will be counted exactly when we process C and consider pairs from different groups. Our algorithm, as described, will count that pair: Suppose without loss of generality, u is in a group processed before v's group? But both groups are processed sequentially. The order of processing groups is arbitrary. In our method, we will multiply contribution for the pair when processing the node that belongs to the later group. At that time, the earlier node is already in the map, so we will multiply by P_u * P_v? Actually careful: The pair (u,v) will be counted exactly once: when processing the group that contains the later node (according to the order we process groups). At that time, we compute total_prod (which includes P of the earlier node) and total_count, and then multiply by P_v^{count} and total_prod. That yields factor P_earlier * P_later. So the product includes both P_u and P_v. The earlier node's P is included via total_prod, the later node's via pow. So the pair contributes exactly once. It doesn't matter which is earlier, as long as we include both factors. So yes, each unordered pair is accounted exactly once.
But we must also consider that when we process the later node, we multiply by total_prod (product of P of earlier nodes) and P_later^{count}. That's correct. However, we need to ensure that we don't double-count by also including the pair when processing the earlier node? No, because when processing the earlier node, the later node was not yet in the map, so it wasn't counted. So each pair counted once.
Thus the algorithm should produce the correct product.
Now, we need to compute d and P for each node in a subtree relative to centroid. But note that d is the difference in red-black counts. Since colors are 0/1, we can assign delta = 1 for red, -1 for black. So d(node) = sum of deltas along path from centroid to node.
However, we must be careful: In the centroid decomposition, when we remove centroid and recursively process subtrees, we need to consider that the edges to children are cut. For each subtree, we will compute new centroid and new d values relative to that new centroid. That's fine.
Now, we need to implement centroid decomposition efficiently.
Implementation steps:
- Read n and edges. Build adjacency list: each node has list of (neighbor, weight, color). We'll store weight mod MOD and delta = (1 if color==0 else -