2

Basically, I am trying to modify Kruskal's algorithm by adding one more condition besides checking whether vertices u and v are not in the same component. I vaguely understand how union-find data structure works, so I wanted to check if I actually got the right idea.

Given that I have an undirected graph G = (V, E) and a set A that contains some vertices in V (subset of vertices A ⊂ V), I want to catch the instances where, for each vertex u in V (loop), u is also found in this set A. I was thinking of using:

(Full Kruskal's algorithm omitted)
original_comp = make_sets(V)
A_comp = make_sets(A)
for each edge (u, v) in E:
   if (find(original_comp, u) == find(A_comp, u)):
      // do something

Would this not work because the set parameter is different (thus different labels)? I just wanted to confirm...

To clarify, I need to know if an edge (u, v) contains one of the vertices in set A. And I was trying to use the Union-Find to achieve this (since find() takes O(1) time), instead of traversing the set A to compare each element... Could anyone tell me if this is possible? Or should I just use an array traversal method?

Thank you.

Ceria
  • 97
  • 2
  • 9
  • 2
    Not 100% sure I understand, but it sounds like you have an edge (u, v), and just want to test whether either or both of u and v are already in some set A. In that case, I would just use a hashtable to store A (keys are vertices; values are unimportant as it's just the existence of the key that we care about). Testing an edge is just two O(1) lookups (one for u, one for v), and vertices can also be inserted into A in O(1) time. – j_random_hacker Aug 15 '15 at 16:45
  • 1
    FWIW, find() is *not* O(1). It's O(α(n)) at best, where α is the inverse Ackermann function – Niklas B. Aug 15 '15 at 17:02
  • Even if you use every quark in the observable universe as an input for α(n), its result is still less than 4. So, I think O(1) is a pretty good approximation. – Juan Lopes Aug 15 '15 at 18:10
  • @j_random_hacker Thank you, I'll use hashtable for it :) – Ceria Aug 16 '15 at 02:28
  • @Ceria: You're welcome :) – j_random_hacker Aug 21 '15 at 12:50

0 Answers0