问题
I have a list of vertices, from which I have to pick a random vertex with probability proportional to deg(v), where deg(v) is a vertex degree. The pseudo code for this operation look like that:
Select u ∈ L with probability deg(u) / Sigma ∀v∈L deg(v)
Where u is the randomly selected vertex, L is the list of vertices and v is a vertex in L. The problem is that I don't understand how to do it. Can someone explain to me, how to get this random vertex. I would greatly appreciate if someone can explain this to me. Pseudo-code will be even more appreciate ;).
回答1:
Simplest solution is to populate a list of size Sum(d(v))
, for each v
- you will hold a reference to v
in exactly d(v)
entries of your list.
Now, select a uniformly distributed variable x
in range [0,Sum(d(v)))
, and return list[x]
This method requires O(n^2)
space (since for simple graphs Sigma(d(v)) is O(n^2)
), and the initialization time is also O(n^2)
, but it is done only once. Assuming you are going to chose a vertex a lot of times, each time you select it, except the first, will be O(1)
[assuming O(1)
randomization function and a random access list].
回答2:
Another solution; still simple and doesn't require any pre-processing or extra memory (if you have a list of edges in the graph):
Choose a random edge, then choose randomly one of the nodes it connects; that's your random vertex. Probability is proportional to the vertices degree - for every node, the probability is
P(v) = sum(P(e: e uses v))/2 = |{e: e uses v}|/(2*|E|) = deg(v)/(2*|E|)
来源:https://stackoverflow.com/questions/11541831/select-element-from-collection-with-probability-proportional-to-element-value