Skip to content

3553. Minimum Weighted Subgraph With the Required Paths II 👍

  • Time: $O(n\log n + q\log n)$
  • Space: $O(n + q)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
 public:
  // Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
  vector<int> minimumWeight(vector<vector<int>>& edges,
                            vector<vector<int>>& queries) {
    const int n = edges.size() + 1;
    const int m = ceil(log2(n));
    vector<int> ans;
    vector<vector<pair<int, int>>> graph(n);
    // jump[i][j] := the 2^j-th ancestor of i
    vector<vector<int>> jump(n, vector<int>(m));
    // depth[i] := the depth of i
    vector<int> depth(n);
    // dist[i] := the distance from root to i
    vector<int> dist(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      const int w = edge[2];
      graph[u].emplace_back(v, w);
      graph[v].emplace_back(u, w);
    }

    dfs(graph, 0, /*prev=*/-1, jump, depth, dist);

    for (int j = 1; j < m; ++j)
      for (int i = 0; i < n; ++i)
        jump[i][j] = jump[jump[i][j - 1]][j - 1];

    for (const vector<int>& query : queries) {
      const int src1 = query[0];
      const int src2 = query[1];
      const int dest = query[2];
      ans.push_back((distance(src1, src2, jump, depth, dist) +
                     distance(src1, dest, jump, depth, dist) +
                     distance(src2, dest, jump, depth, dist)) /
                    2);
    }

    return ans;
  }

 private:
  void dfs(const vector<vector<pair<int, int>>>& graph, int u, int prev,
           vector<vector<int>>& jump, vector<int>& depth, vector<int>& dist) {
    for (const auto& [v, w] : graph[u]) {
      if (v == prev)
        continue;
      jump[v][0] = u;
      depth[v] = depth[u] + 1;
      dist[v] = dist[u] + w;
      dfs(graph, v, u, jump, depth, dist);
    }
  }

  // Returns the lca(u, v) by binary jump.
  int getLCA(int u, int v, const vector<vector<int>>& jump,
             const vector<int>& depth) {
    // v is always deeper than u.
    if (depth[u] > depth[v])
      return getLCA(v, u, jump, depth);
    // Jump v to the same height of u.
    for (int j = 0; j < jump[0].size(); ++j)
      if (depth[v] - depth[u] >> j & 1)
        v = jump[v][j];
    if (u == v)
      return u;
    // Jump u and v to the node right below the lca.
    for (int j = jump[0].size() - 1; j >= 0; --j)
      if (jump[u][j] != jump[v][j]) {
        u = jump[u][j];
        v = jump[v][j];
      }
    return jump[u][0];
  }

  // Returns the distance between u and v.
  int distance(int u, int v, const vector<vector<int>>& jump,
               const vector<int>& depth, const vector<int>& dist) {
    const int lca = getLCA(u, v, jump, depth);
    return dist[u] + dist[v] - 2 * dist[lca];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Solution {
  // Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
  public int[] minimumWeight(int[][] edges, int[][] queries) {
    final int n = edges.length + 1;
    final int m = (int) Math.ceil(Math.log(n) / Math.log(2));
    int[] ans = new int[queries.length];
    List<Pair<Integer, Integer>>[] graph = new List[n];
    // jump[i][j] := the 2^j-th ancestor of i
    int[][] jump = new int[n][m];
    // depth[i] := the depth of i
    int[] depth = new int[n];
    // dist[i] := the distance from root to i
    int[] dist = new int[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      final int w = edge[2];
      graph[u].add(new Pair<>(v, w));
      graph[v].add(new Pair<>(u, w));
    }

    dfs(graph, 0, /*prev=*/-1, jump, depth, dist);

    for (int j = 1; j < m; ++j)
      for (int i = 0; i < n; ++i)
        jump[i][j] = jump[jump[i][j - 1]][j - 1];

    for (int i = 0; i < queries.length; ++i) {
      final int src1 = queries[i][0];
      final int src2 = queries[i][1];
      final int dest = queries[i][2];
      ans[i] = (distance(src1, src2, jump, depth, dist) + distance(src1, dest, jump, depth, dist) +
                distance(src2, dest, jump, depth, dist)) /
               2;
    }

    return ans;
  }

  private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int[][] jump, int[] depth,
                   int[] dist) {
    for (Pair<Integer, Integer> pair : graph[u]) {
      final int v = pair.getKey();
      final int w = pair.getValue();
      if (v == prev)
        continue;
      jump[v][0] = u;
      depth[v] = depth[u] + 1;
      dist[v] = dist[u] + w;
      dfs(graph, v, u, jump, depth, dist);
    }
  }

  // Returns the lca(u, v) by binary jump.
  private int getLCA(int u, int v, int[][] jump, int[] depth) {
    // v is always deeper than u.
    if (depth[u] > depth[v])
      return getLCA(v, u, jump, depth);
    // Jump v to the same height of u.
    for (int j = 0; j < jump[0].length; ++j)
      if ((depth[v] - depth[u] >> j & 1) == 1)
        v = jump[v][j];
    if (u == v)
      return u;
    // Jump u and v to the node right below the lca.
    for (int j = jump[0].length - 1; j >= 0; --j)
      if (jump[u][j] != jump[v][j]) {
        u = jump[u][j];
        v = jump[v][j];
      }
    return jump[u][0];
  }

  // Returns the distance between u and v.
  private int distance(int u, int v, int[][] jump, int[] depth, int[] dist) {
    final int lca = getLCA(u, v, jump, depth);
    return dist[u] + dist[v] - 2 * dist[lca];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class Solution:
  # Similar to 2846. Minimum Edge Weight Equilibrium Queries in a Tree
  def minimumWeight(
      self,
      edges: list[list[int]],
      queries: list[list[int]]
  ) -> list[int]:
    n = len(edges) + 1
    m = math.ceil(math.log2(n))
    graph = [[] for _ in range(n)]
    jump = [[0] * m for _ in range(n)]  # jump[i][j] := the 2^j-th ancestor of i
    depth = [0] * n  # depth[i] := the depth of i
    dist = [0] * n  # dist[i] := the distance from root to i

    for u, v, w in edges:
      graph[u].append((v, w))
      graph[v].append((u, w))

    self._dfs(graph, 0, -1, jump, depth, dist)

    for j in range(1, m):
      for i in range(n):
        jump[i][j] = jump[jump[i][j - 1]][j - 1]

    return [(self._distance(src1, src2, jump, depth, dist) +
             self._distance(src1, dest, jump, depth, dist) +
             self._distance(src2, dest, jump, depth, dist)) // 2
            for src1, src2, dest in queries]

  def _dfs(
      self,
      graph: list[list[tuple[int, int]]],
      u: int,
      prev: int,
      jump: list[list[int]],
      depth: list[int],
      dist: list[int]
  ) -> None:
    for v, w in graph[u]:
      if v == prev:
        continue
      jump[v][0] = u
      depth[v] = depth[u] + 1
      dist[v] = dist[u] + w
      self._dfs(graph, v, u, jump, depth, dist)

  def _getLCA(
      self,
      u: int,
      v: int,
      jump: list[list[int]],
      depth: list[int]
  ) -> int:
    """Returns the lca(u, v) by binary jump."""
    # v is always deeper than u.
    if depth[u] > depth[v]:
      return self._getLCA(v, u, jump, depth)
    # Jump v to the same height of u.
    for j in range(len(jump[0])):
      if depth[v] - depth[u] >> j & 1:
        v = jump[v][j]
    if u == v:
      return u
    # Jump u and v to the node right below the lca.
    for j in range(len(jump[0]) - 1, -1, -1):
      if jump[u][j] != jump[v][j]:
        u = jump[u][j]
        v = jump[v][j]
    return jump[u][0]

  def _distance(
      self,
      u: int,
      v: int,
      jump: list[list[int]],
      depth: list[int],
      dist: list[int]
  ) -> int:
    """Returns the distance between u and v."""
    lca = self._getLCA(u, v, jump, depth)
    return dist[u] + dist[v] - 2 * dist[lca]