Skip to main content
Back to problems
#3559
Hard Algorithms

Number of ways to assign edge weights ii

Array Math Dynamic Programming Bit Manipulation Tree Depth-First Search
59.5% acceptance
Feb 25, 2026
57
1
There is an undirected tree with n nodes labeled from 1 to n, rooted at node 1. The tree is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that there is an edge between nodes ui and vi. 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 u and v is the total weight of all edges in the path connecting them. You are given a 2D integer array queries. For each queries[i] = [ui, vi], determine the number of ways to assign weights to edges in the path such that the cost of the path between ui and vi is odd. Return an array answer, where answer[i] is the number of valid assignments for queries[i]. Since the answer may be large, apply modulo 109 + 7 to each answer[i]. Note: For each query, disregard all edges not in the path between node ui and vi.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn assign_edge_weights(edges: Vec<Vec<i32>>, queries: Vec<Vec<i32>>) -> Vec<i32> {
    // Path length from u to v = depth[u] + depth[v] - 2*depth[lca(u,v)].
    // Ways for d edges with odd sum = 2^(d-1) if d>=1, else 0.
    
    let n = edges.len() + 1;
    let mut adj: Vec<Vec<usize>> = vec![vec![]; n + 1];
    for e in &edges {
      let (u, v) = (e[0] as usize, e[1] as usize);
      adj[u].push(v);
      adj[v].push(u);
    }
    
    const MOD: i64 = 1_000_000_007;
    let log = 17;
    let mut parent = vec![vec![0usize; log]; n + 1];
    let mut depth = vec![0i32; n + 1];
    
    // BFS from root 1
    let mut visited = vec![false; n + 1];
    let mut queue = std::collections::VecDeque::new();
    let mut order = Vec::with_capacity(n);
    queue.push_back(1usize);
    visited[1] = true;
    parent[1][0] = 1;
    while let Some(u) = queue.pop_front() {
      order.push(u);
      for &v in &adj[u] {
        if !visited[v] {
          visited[v] = true;
          parent[v][0] = u;
          depth[v] = depth[u] + 1;
          queue.push_back(v);
        }
      }
    }
    
    // Build binary lifting
    for k in 1..log {
      for &u in &order {
        parent[u][k] = parent[parent[u][k-1]][k-1];
      }
    }
    
    let lca = |mut u: usize, mut v: usize| -> usize {
      if depth[u] < depth[v] { std::mem::swap(&mut u, &mut v); }
      let diff = (depth[u] - depth[v]) as usize;
      for k in 0..log {
        if (diff >> k) & 1 == 1 { u = parent[u][k]; }
      }
      if u == v { return u; }
      for k in (0..log).rev() {
        if parent[u][k] != parent[v][k] {
          u = parent[u][k];
          v = parent[v][k];
        }
      }
      parent[u][0]
    };
    
    // Precompute powers of 2
    let max_len = n + 2;
    let mut pow2 = vec![1i64; max_len + 1];
    for i in 1..=max_len { pow2[i] = pow2[i-1] * 2 % MOD; }
    
    queries.iter().map(|q| {
      let (u, v) = (q[0] as usize, q[1] as usize);
      if u == v { return 0; }
      let l = lca(u, v);
      let path_len = (depth[u] + depth[v] - 2 * depth[l]) as usize;
      if path_len == 0 { 0i32 }
      else { pow2[path_len - 1] as i32 }
    }).collect()
  }
}