Skip to content

1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree 👍

  • Time: $O(n^2\lg^* n)$
  • Space: $O(n)$
 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
85
86
87
88
89
90
91
92
93
class UnionFind {
 public:
  UnionFind(int n) : id(n), rank(n) {
    iota(begin(id), end(id), 0);
  }

  void unionByRank(int u, int v) {
    const int i = find(u);
    const int j = find(v);
    if (i == j)
      return;
    if (rank[i] < rank[j]) {
      id[i] = id[j];
    } else if (rank[i] > rank[j]) {
      id[j] = id[i];
    } else {
      id[i] = id[j];
      ++rank[j];
    }
  }

  int find(int u) {
    return id[u] == u ? u : id[u] = find(id[u]);
  }

 private:
  vector<int> id;
  vector<int> rank;
};

class Solution {
 public:
  vector<vector<int>> findCriticalAndPseudoCriticalEdges(
      int n, vector<vector<int>>& edges) {
    vector<int> criticalEdges;
    vector<int> pseudoCriticalEdges;

    // Record the index information, so edges[i] := (u, v, weight, index).
    for (int i = 0; i < edges.size(); ++i)
      edges[i].push_back(i);

    // Sort by weight.
    sort(
        begin(edges), end(edges),
        [](const vector<int>& a, const vector<int>& b) { return a[2] < b[2]; });

    const int mstWeight = getMSTWeight(n, edges, {}, -1);

    for (const vector<int>& edge : edges) {
      const int index = edge[3];
      // Deleting `e` makes the MST weight increase or can't form a MST.
      if (getMSTWeight(n, edges, {}, index) > mstWeight)
        criticalEdges.push_back(index);
      // If an edge can be in any MST, we can always add `edge` to the edge set.
      else if (getMSTWeight(n, edges, edge, -1) == mstWeight)
        pseudoCriticalEdges.push_back(index);
    }

    return {criticalEdges, pseudoCriticalEdges};
  }

 private:
  int getMSTWeight(int n, const vector<vector<int>>& edges,
                   const vector<int>& firstEdge, int deletedEdgeIndex) {
    int mstWeight = 0;
    UnionFind uf(n);

    if (!firstEdge.empty()) {
      uf.unionByRank(firstEdge[0], firstEdge[1]);
      mstWeight += firstEdge[2];
    }

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      const int weight = edge[2];
      const int index = edge[3];
      if (index == deletedEdgeIndex)
        continue;
      if (uf.find(u) == uf.find(v))
        continue;
      uf.unionByRank(u, v);
      mstWeight += weight;
    }

    const int root = uf.find(0);
    for (int i = 0; i < n; ++i)
      if (uf.find(i) != root)
        return INT_MAX;

    return mstWeight;
  }
};
 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
85
86
87
88
class UnionFind {
  public UnionFind(int n) {
    id = new int[n];
    rank = new int[n];
    for (int i = 0; i < n; ++i)
      id[i] = i;
  }

  public void unionByRank(int u, int v) {
    final int i = find(u);
    final int j = find(v);
    if (i == j)
      return;
    if (rank[i] < rank[j]) {
      id[i] = id[j];
    } else if (rank[i] > rank[j]) {
      id[j] = id[i];
    } else {
      id[i] = id[j];
      ++rank[j];
    }
  }

  public int find(int u) {
    return id[u] == u ? u : (id[u] = find(id[u]));
  }

  private int[] id;
  private int[] rank;
}

class Solution {
  public List<List<Integer>> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {
    List<Integer> criticalEdges = new ArrayList<>();
    List<Integer> pseudoCriticalEdges = new ArrayList<>();

    // Record the index information, so edges[i] := (u, v, weight, index).
    for (int i = 0; i < edges.length; ++i)
      edges[i] = new int[] {edges[i][0], edges[i][1], edges[i][2], i};

    // Sort by weight.
    Arrays.sort(edges, (a, b) -> a[2] - b[2]);

    final int mstWeight = getMSTWeight(n, edges, new int[] {}, -1);

    for (int[] edge : edges) {
      final int index = edge[3];
      // Deleting `e` makes the MST weight increase or can't form a MST.
      if (getMSTWeight(n, edges, new int[] {}, index) > mstWeight)
        criticalEdges.add(index);
      // If an edge can be in any MST, we can always add `edge` to the edge set.
      else if (getMSTWeight(n, edges, edge, -1) == mstWeight)
        pseudoCriticalEdges.add(index);
    }

    return new ArrayList<>(Arrays.asList(criticalEdges, pseudoCriticalEdges));
  }

  private int getMSTWeight(int n, int[][] edges, int[] firstEdge, int deletedEdgeIndex) {
    int mstWeight = 0;
    UnionFind uf = new UnionFind(n);

    if (firstEdge.length == 4) {
      uf.unionByRank(firstEdge[0], firstEdge[1]);
      mstWeight += firstEdge[2];
    }

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      final int weight = edge[2];
      final int index = edge[3];
      if (index == deletedEdgeIndex)
        continue;
      if (uf.find(u) == uf.find(v))
        continue;
      uf.unionByRank(u, v);
      mstWeight += weight;
    }

    final int root = uf.find(0);
    for (int i = 0; i < n; ++i)
      if (uf.find(i) != root)
        return Integer.MAX_VALUE;

    return mstWeight;
  }
}
 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
class UnionFind:
  def __init__(self, n: int):
    self.id = list(range(n))
    self.rank = [0] * n

  def unionByRank(self, u: int, v: int) -> None:
    i = self.find(u)
    j = self.find(v)
    if i == j:
      return
    if self.rank[i] < self.rank[j]:
      self.id[i] = self.id[j]
    elif self.rank[i] > self.rank[j]:
      self.id[j] = self.id[i]
    else:
      self.id[i] = self.id[j]
      self.rank[j] += 1

  def find(self, u: int) -> int:
    if self.id[u] != u:
      self.id[u] = self.find(self.id[u])
    return self.id[u]


class Solution:
  def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
    criticalEdges = []
    pseudoCriticalEdges = []

    # Record the index information, so edges[i] := (u, v, weight, index).
    for i in range(len(edges)):
      edges[i].append(i)

    # Sort by weight.
    edges.sort(key=lambda x: x[2])

    def getMSTWeight(firstEdge: List[int], deletedEdgeIndex: int) -> Union[int, float]:
      mstWeight = 0
      uf = UnionFind(n)

      if firstEdge:
        uf.unionByRank(firstEdge[0], firstEdge[1])
        mstWeight += firstEdge[2]

      for u, v, weight, index in edges:
        if index == deletedEdgeIndex:
          continue
        if uf.find(u) == uf.find(v):
          continue
        uf.unionByRank(u, v)
        mstWeight += weight

      root = uf.find(0)
      if any(uf.find(i) != root for i in range(n)):
        return math.inf

      return mstWeight

    mstWeight = getMSTWeight([], -1)

    for edge in edges:
      index = edge[3]
      # Deleting `e` makes the MST weight increase or can't form a MST.
      if getMSTWeight([], index) > mstWeight:
        criticalEdges.append(index)
      # If an edge can be in any MST, we can always add `edge` to the edge set.
      elif getMSTWeight(edge, -1) == mstWeight:
        pseudoCriticalEdges.append(index)

    return [criticalEdges, pseudoCriticalEdges]