问题
Given two sets, each containing integer values, how could one find a set containing all possible pair-wise ORs of the values of those two sets? E.g. (all numbers are binary)
{1, 10} x {100, 1000} = {101, 1001, 110, 1010}
{1, 10} x {11, 101} = {11, 101, 111}
The first example results in full four combinations, while the second one only results in three, since both sets share some bits. Obviously the result can be calculated in O(m*n), but is there a faster way of solving this, taking into account that in many cases the size of the result would be less than m*n?
In some of the cases the resulting set is significantly smaller than m*n (e.g. {1, 11, 111} x {10, 110} = {11, 111}) - but I can't quite pinpoint the exact nature of all those cases in a generic-enough way to get an algorithm. Ideally it should run in O(r), where r is the size of the resulting set. There may be some way to partition source sets, build-up the result using a dynamic programming approach, or do something else in that vein, but for now I can't find it.
回答1:
Although I don't know much about it, I wonder if, depending on the cardinality of the data, using a trie for one set could improve efficiency. When traversing the other set to or with the indexed set, whole branches of the tree may be skipped if it can be determined that bits are matched for the current integer in the indexed set.
Another optimization could be to skip all pairings of bit-length n if we already have 2^(n-1) results of that length; for example, there are eight possible integers, four bits in length.
来源:https://stackoverflow.com/questions/22234322/finding-a-set-of-all-pair-wise-ors-of-two-sets-of-integers