The best way to calculate all nodes at a distance less than k from m given nodes

A size graph is given nand a subset of the size t21 of its nodes is indicated. Find all the nodes that are in distance <=kfrom ALL nodes of the subset.

eg. A-> B-> C-> D-> E - graph, subset= {A, C}, k= 2.

Now E is at a distance <= 2 from C, but not from A, so it should not be counted.

I was thinking of starting Breadth First Search from each node in a subset and intersecting the corresponding answers.
Is it possible to optimize it?

I looked at a lot of posts on SO, but they all go to kd trees, which I don't understand, is there any other way?

+4
source share
2 answers

I can think of two non-asymptotic (I believe) optimizations:

  • If you have finished working with BFS from one of the nodes in the subset, delete all nodes with a distance> k from it
  • Start with two nodes in the subset whose distance is greatest to get the smallest possible remaining graph.

Of course, this does not help if k is large (close to n), I have no idea in this case. I am sure, however, that the k / d trees are not applicable to general graphs :)

+2
source

The Nicklas B optimization can be applied to both of the following optimizations.

Optimization # 1: Modify BFS to perform the intersection as it launches, not after words.

, BFS - . , BFS redudant. , , ( BFS). , BFS.

, , , "ToVisit" "", .

BFS :

  • ToVisit BFS. ToVisit , .
  • , , ToVisit, . ToVisit node.
  • node BFS, ToVisit - . ToVisit node.

, ToVisit , m k, , N.

# 2: , , . . k, , O (VE).

, O (V * M * Q), Q - , M - , V - , , O (M * Q) > O (E), . , , k , O (V).

.

  • "kCount [A] [k] = k A". . " , , " , O (m) > O (sqrt (V)), O (m ^ 2), . k . .

  • - "kMax [A] = max k A", hashmap/dictionary. k >= , , kCount [A] [kMax [A]] < ( ), A.

  • : "kFrom [A] [k] = k, A", k 0 , / / , /. ***, <= k A.

  • - "dist [A] [B] = A B", , /. .

* , k A, O (V ^ 3) , , . , , , , k. , dist > k dist <= k. dist <= k dist <= k , , .

0

Source: https://habr.com/ru/post/1537699/


All Articles