[英]Given two unsorted arrays find the number of pairs where A[i] > X and B[i] > Y
We are given two unsorted arrays.我们得到两个未排序的 arrays。 We have to find the number of pairs such that for each pair A[i] > X and B[i] > Y. We will have to process 1 million such queries where each query will have different X and Y given.我们必须找到对的数量,使得每对 A[i] > X 和 B[i] > Y。我们将必须处理 100 万个这样的查询,其中每个查询将给出不同的 X 和 Y。 The length of the array will also be up to 1 million.数组的长度也将达到 100 万。
Constraints:约束:
1 <=A[i],B[i],X,Y <=10^9 1<= A.size, B.size, Number of Queries <= 10^6 1 <=A[i],B[i],X,Y <=10^9 1<= A.size, B.size, 查询数 <= 10^6
For ex:例如:
A = [7,2,10,15,12,9]
B = [10,8,5,3,4,7]
Queries:查询:
X Y o/p
9 3 2 (As we have 2 pairs which satisfy above condition (10,5), (12,4))
6 4 3 (As we have 3 pairs which satisfy above condition (7,10), (10,5), (9,7))
Is there any better approach than brute force as we have 1 million such queries?由于我们有 100 万个这样的查询,有没有比蛮力更好的方法?
If the queries are provided offline, there's no need for a quad tree and we can solve this in O(n log n)
.如果查询是离线提供的,则不需要四叉树,我们可以在O(n log n)
中解决这个问题。 Insert all query-pairs and array-pairs into one list, sorted by X
or a
(if an X
is equal to an a
, place the query pair after the array pair).将所有查询对和数组对插入到一个列表中,按X
或a
排序(如果X
等于a
,则将查询对放在数组对之后)。 Process the pairs in the list by descending order (of a
or X
).按降序( a
或X
)处理列表中的对。 If it's an array pair, insert it into an order-statistic tree ordered by b
.如果它是一个数组对,则将其插入到按b
排序的顺序统计树中。 If it's a query, look up in the tree the count of tree nodes (these are array pairs) that have b > Y
(we already know all pairs in the tree have a > X
).如果是查询,则在树中查找具有b > Y
的树节点(这些是数组对)的计数(我们已经知道树中的所有对都有a > X
)。
A quadtree would be better than brute force.四叉树会比蛮力更好。 Interpret the pairs (a, b) as 2D co-ordinates of points, and insert them into a quadtree.将 (a, b) 对解释为点的 2D 坐标,并将它们插入四叉树。 Each node in the quadtree should also store its cardinality, ie the number of points within the area represented by that node.四叉树中的每个节点还应存储其基数,即该节点表示的区域内的点数。 Each point-counting query can then be answered recursively on the quadtree, where the base case is a node whose area is either completely contained within the region a > X && b > Y
(in which case return the node's cardinality), or completely disjoint from it (in which case return 0).然后可以在四叉树上递归地回答每个点计数查询,其中基本情况是一个节点,其区域完全包含在区域a > X && b > Y
内(在这种情况下返回节点的基数),或者完全不相交从它(在这种情况下返回 0)。
Other similar data structures such as a kd tree could be used similarly.可以类似地使用其他类似的数据结构,例如kd 树。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.