2

INPUT: weighted undirected graph in the form of adjacency list

OUTPUT: adjacency list without the edge e

Naive approach is:

for(int i = 0; i < adj.get(e.s).size(); i++) { // loop through adjacent of s
  if(adj.get(e.s).get(i).v == e.t) {           // find t and remove it
    adj.get(e.s).remove(i); 
    break;
  }
}
for(int i = 0; i < adj.get(e.t).size(); i++) { // loop through adjacent of t
  if(adj.get(e.t).get(i).v == e.s) {           // find s and remove it
    adj.get(e.t).remove(i); 
    break;
  }
}
O(k) - k is number of adjacent vertices

A faster approach is to use adjacencyMatrix but my algorithm has alot of traversals involved and looping through each dimension in the adjMat costs more despite a O(1) edge removal.

How can I speed up removing an edge? (used in generating a MST (kruskal))

iluvAS
  • 233
  • 2
  • 5

1 Answers1

1

I didn't realize what is your problem with Kruskal algorithm. To me, a usual Kruskal has time complexity $O(E \ log E)$ that $E$ is the number of edges in a graph, and I don't have any difficulty to ignore those edges which make a cycle.

To answer you question, all adjacency lists, maintaining adjacent vertices, can be sorted in an ascending order. Then, you can find the position of each adjacent node with $O(log N)$, where $N$ is the number of vertices.

You should also define two one-dimensional arrays, $nex$ and $pre$ for each adjacency list, where $nex$ maintains the position of next vertex in an adjacency list, and $pre$ holds the previous position.

When edge $e = (a, b)$ is about to be removed, the position of $b$ in the adjacency list of $a$ can be found with $O (log \ N)$.

Then, do two following steps to remove $a \to b$:

  • $nex [ \ pre [b] \ ] = nex [b]$
  • $pre [ \ nex [b] \ ] = pre [b]$

Do it also in the adjacency list of $b$ to remove $b \to a$.

If you want to traverse in an adjacency list, the next index can be reached by the means of $nex$ array.

To traverse an adjacency list from the beginning a random value, as a dump, can be utilized since the first node might be removed.

beginner1010
  • 168
  • 7