简体   繁体   English

有多少条线段将在一个平面内与水平线相交? 找到这个的最有效方法是什么

[英]how many line segments will intersect in a plane will intersect with a horizontal line ? what will be the most effective way to find this

I'm trying to solve this Cyberchef challenge :我正在尝试解决这个 Cyber​​chef 挑战

You are given N points in a plane (numbered 1 through N);给定平面上的 N 个点(编号为 1 到 N); for each valid i, the i-th point is Pi=(i,Ai).对于每个有效的 i,第 i 个点是 Pi=(i,Ai)。 There are N−1 line segments between them (numbered 1 through N−1);它们之间有 N-1 条线段(编号为 1 到 N-1); for each valid i, the i-th line segment is formed by connecting the points Pi and Pi+1.对于每个有效的 i,连接点 Pi 和 Pi+1 形成第 i 条线段。

You are given Q horizontal line segments .你得到 Q 条水平线段。 Each query horizontal line segment is denoted by two points, from a point (x1,y) to a point (x2,y) (where it stops and does not propagate further).每个查询水平线段由两个点表示,从一个点 (x1,y) 到一个点 (x2,y)(它停止并且不再进一步传播)。 For Every Horizontal line segment, you have to find the number of line segments from those (N-1 line segments) it collides with on the way.对于每个水平线段,您必须从它在途中碰撞的那些(N-1 条线段)中找出线段的数量。

So this is the problem where:所以这是问题所在:

  • 2<=N<= 100000 2<=N<= 100000
  • 1<=Q<= 100000 1<=Q<= 100000

Can anyone teach me what approach will be best and most effective in terms of time complexity?谁能教我什么方法在时间复杂度方面最好和最有效?

So you have the only polyline and want to check many queries for intersection with horizontal segments.因此,您拥有唯一的折线,并且想要检查与水平线段相交的许多查询。

It is worth to build some kind of binary space partitioning (BSP) over that polyline.值得在该折线上构建某种二进制空间分区(BSP) In this case you can check for intersection in O(log(n)) time, so overall time is O(nlogn)+O(qlogn) (building and checking)在这种情况下,您可以在O(log(n))时间内检查交集,因此总时间为O(nlogn)+O(qlogn) (构建和检查)


If yout polyline fortunately is convex polygon (without one closing edge), things are quite simpler - just sort edges by Y-coordinate and check only those intersecting query Y (binary search, log(n) per query).如果你的折线幸运的是多边形(没有一个闭合边),事情就很简单了——只需按 Y 坐标对边进行排序并只检查那些相交的查询 Y(二元搜索,每个查询的 log(n))。 In general case (non-convex) your polyline might look like WMWMWMW and you have to check too many edges.在一般情况下(非凸面),您的折线可能看起来像WMWMWMW ,您必须检查太多边。

I used kd tree to solve this problem.我用 kd 树来解决这个问题。 Also dont ask questions that are on-going challenges.也不要问正在进行的挑战的问题。

所以扫描线算法是你基本上需要知道的,以解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM