Efficient Cartesian Product algorithm

后端 未结 6 1681
太阳男子
太阳男子 2020-11-29 07:00

Can somebody please demonstrate for me a more efficient Cartesian product algorithm than the one I am using currently (assuming there is one). I\'ve looked around SO and go

6条回答
  •  再見小時候
    2020-11-29 07:33

    I can't propose anything better, than O(n^2), because that's the size of the output, and the algorithm hence can't be any faster.

    What I can suggest is using another approach to whether you need to compute product. For example, you may not even need the product set P if only you are going to query whether certain elements belong to it. You only need the information about the sets it's composed of.

    Indeed (pseudocode)

    bool IsInSet(pair (x,y), CartesianProductSet P)
    {
       return IsInHash(x,P.set[1]) && IsInHash(y,P.set[2])
    }
    

    where Cartesian product is calculated like this:

    // Cartesian product of A and B is
    P.set[1]=A; P.set[2]=B;
    

    If you implement sets as hashes, then lookup in a cartesian product of m sets is just a lookup in m hashes you get for free. Construction of the cartesian product and IsInSet lookup each take O(m) time, where m is a number of sets you multiply, and it's much less than n--size of each set.

提交回复
热议问题