Class Solution
-
- All Implemented Interfaces:
public final class Solution3559 - Number of Ways to Assign Edge Weights II.
Hard
There is an undirected tree with
nnodes labeled from 1 ton, rooted at node 1. The tree is represented by a 2D integer arrayedgesof lengthn - 1, where <code>edgesi = u<sub>i</sub>, v<sub>i</sub></code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.
The cost of a path between any two nodes
uandvis the total weight of all edges in the path connecting them.You are given a 2D integer array
queries. For each <code>queriesi = u<sub>i</sub>, v<sub>i</sub></code>, determine the number of ways to assign weights to edges in the path such that the cost of the path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> is odd.Return an array
answer, whereanswer[i]is the number of valid assignments forqueries[i].Since the answer may be large, apply modulo <code>10<sup>9</sup> + 7</code> to each
answer[i].Note: For each query, disregard all edges not in the path between node <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.
Example 1:
Input: edges = [1,2], queries = [1,1,1,2]
Output: 0,1
Explanation:
Query
[1,1]: The path from Node 1 to itself consists of no edges, so the cost is 0. Thus, the number of valid assignments is 0.Query
[1,2]: The path from Node 1 to Node 2 consists of one edge (1 → 2). Assigning weight 1 makes the cost odd, while 2 makes it even. Thus, the number of valid assignments is 1.
Example 2:
Input: edges = [1,2,1,3,3,4,3,5], queries = [1,4,3,4,2,5]
Output: 2,1,4
Explanation:
Query
[1,4]: The path from Node 1 to Node 4 consists of two edges (1 → 3and3 → 4). Assigning weights (1,2) or (2,1) results in an odd cost. Thus, the number of valid assignments is 2.Query
[3,4]: The path from Node 3 to Node 4 consists of one edge (3 → 4). Assigning weight 1 makes the cost odd, while 2 makes it even. Thus, the number of valid assignments is 1.Query
[2,5]: The path from Node 2 to Node 5 consists of three edges (2 → 1, 1 → 3, and3 → 5). Assigning (1,2,2), (2,1,2), (2,2,1), or (1,1,1) makes the cost odd. Thus, the number of valid assignments is 4.
Constraints:
<code>2 <= n <= 10<sup>5</sup></code>
edges.length == n - 1<code>edgesi == u<sub>i</sub>, v<sub>i</sub></code>
<code>1 <= queries.length <= 10<sup>5</sup></code>
<code>queriesi == u<sub>i</sub>, v<sub>i</sub></code>
<code>1 <= u<sub>i</sub>, v<sub>i</sub><= n</code>
edgesrepresents a valid tree.