Let's say I have a vector of vectors:
std::vector<std::vector<int> > vec;
Now, in my program, this vector contains groups of nodes that create a cycle in a graph. They create the strongly connected component if they are intersected.
I need to loop over this vector and effectively find those vectors, which are intersected and afterwards, join those. It can be done with sets by brute force set_intersection and set_union, but it would be very slow.
As an example, if I have vectors A-D of simple int elements, where A,B,D are intersected.
A = [1,2,3,4]
B = [5,6,7]
C = [8,9]
D = [3,4,6,10]
and I want this result:
s1 = [1,2,3,4,5,6,7,10]
s2 = [8,9]
Now, I have tried multiple things over last few hours, but simple googling shows that set_intersection would be quite slow approach and I would have to loop over all the sets of nodes multiple times (I think it would be N*(N + 1)/2, so O(N2) without heuristics).
I need to do this effectively, so the thing I have in mind is to loop over all the nodes and note down where I found the original node, then group them together in one search, if possible. However I am unable to find nor design such an algorithm to be effective enough, so I would appreciate some help or ideas on how to approach this.
Thank you.