Skip to content

3559. Number of Ways to Assign Edge Weights II

Description

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.

 

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 → 3 and 3 → 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, and 3 → 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:

  • 2 <= n <= 105
  • edges.length == n - 1
  • edges[i] == [ui, vi]
  • 1 <= queries.length <= 105
  • queries[i] == [ui, vi]
  • 1 <= ui, vi <= n
  • edges represents a valid tree.

 

Solutions

Solution: Binary Lifting + Depth-First Search

  • Time complexity: O(nlogn+qlogn)
  • Space complexity: O(nlogn)

 

JavaScript

js
/**
 * @param {number[][]} edges
 * @param {number[][]} queries
 * @return {number[]}
 */
const assignEdgeWeights = function (edges, queries) {
  const MODULO = BigInt(10 ** 9 + 7);
  const n = edges.length + 1;
  const maxLog = 32 - Math.clz32(n);
  const depth = Array.from({ length: n + 1 }, () => 0);
  const graph = Array.from({ length: n + 1 }, () => []);
  const parent = Array.from({ length: maxLog }, () => {
    return new Array(n + 1).fill(-1);
  });

  for (const [u, v] of edges) {
    graph[u].push(v);
    graph[v].push(u);
  }

  const dfs = (node, prev) => {
    for (const neighbor of graph[node]) {
      if (neighbor === prev) continue;

      parent[0][neighbor] = node;
      depth[neighbor] = depth[node] + 1;
      dfs(neighbor, node);
    }
  };

  dfs(1, -1);

  for (let log = 1; log < maxLog; log++) {
    for (let node = 1; node <= n; node++) {
      const prev = parent[log - 1][node];

      if (prev === -1) continue;

      parent[log][node] = parent[log - 1][prev];
    }
  }

  const lca = (a, b) => {
    if (depth[a] < depth[b]) {
      return lca(b, a);
    }

    for (let log = maxLog - 1; log >= 0; log--) {
      const prev = parent[log][a];

      if (prev !== -1 && depth[prev] >= depth[b]) {
        a = prev;
      }
    }

    if (a === b) return b;

    for (let log = maxLog - 1; log >= 0; log--) {
      if (parent[log][a] !== -1 && parent[log][a] !== parent[log][b]) {
        a = parent[log][a];
        b = parent[log][b];
      }
    }

    return parent[0][a];
  };

  return queries.map(([u, v]) => {
    if (u === v) return 0;

    const ancestor = lca(u, v);
    const d = depth[u] + depth[v] - 2 * depth[ancestor];

    return modPow(2, d - 1, MODULO);
  });
};

function modPow(base, exp, mod) {
  let result = 1n;

  base = BigInt(base);
  exp = BigInt(exp);

  while (exp) {
    if (exp % 2n) {
      result = (result * base) % mod;
    }

    base = (base * base) % mod;
    exp /= 2n;
  }

  return Number(result);
}

Released under the MIT license