Find number of pairs of disjoint sets in a list of sets

强颜欢笑 提交于 2019-12-08 01:18:25

问题


The problem statement is as follows: given a list of n sets, each containing k integers, find the number of pairs of disjoint sets. Suppose the possible elements of the sets are positive and bounded above by c > n, and suppose k << n.

I'm trying to come up with an efficient algorithm to solve this faster than O(kn^2), which is the runtime of the naive solution.

The best strategy I could come up with involves iterating through each set in the list, and hashing the elements of the set, such that each element in the set maps to a set of the indices of the sets that contain it. Then, for the current set in the iteration, use its c elements as keys, and consider the union of the c sets of indices that are given as values by the hashtable. This resulting set of indices represents the number of sets encountered thusfar that are nondisjoint with the current set, which we can use to find the number of disjoint sets. Summing this value over the entire iteration yields a correct answer. However, since the union operation is O(n), this strategy does no better than the naive solution.

What is the most efficient possible solution for this problem?


回答1:


As k << n, you can reduce the complexity by:

  • Sorting each set, which can be in n * k * log(k)
  • Then sorting all sets by first last element, n * log(n)

Now comparing needs n * (n - 1) operations, which are:

  • Either comparing s1.Last to s2.First (which should be most cases, as k << n)
  • Or effectively search for s1 s2 intersection which is max in k, considering s1 and s2 are sorted


来源:https://stackoverflow.com/questions/53797576/find-number-of-pairs-of-disjoint-sets-in-a-list-of-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!