-2

I’m trying to solve this Cyberchef challenge:

You are given N points in a plane (numbered 1 through N); for each valid i, the i-th point is Pi=(i,Ai). There are N−1 line segments between them (numbered 1 through N−1); for each valid i, the i-th line segment is formed by connecting the points Pi and Pi+1.

You are given Q horizontal line segments . 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). 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.

So this is the problem where:

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

Can anyone teach me what approach will be best and most effective in terms of time complexity?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

3 Answers3

1

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. In this case you can check for intersection in O(log(n)) time, so overall time is O(nlogn)+O(qlogn) (building and checking)


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). In general case (non-convex) your polyline might look like WMWMWMW and you have to check too many edges.

MBo
  • 77,366
  • 5
  • 53
  • 86
  • sorry i down't know hwat is polyline or BSP, where ccan i learn in more detail about your approach ? –  Mar 11 '20 at 10:09
  • Emm... Google and computational geometry books? – MBo Mar 11 '20 at 10:10
  • polyline is common term. binary space partitioning - wide class of different data structures. – MBo Mar 11 '20 at 10:18
1

I used k-d tree to solve this problem. Also dont ask questions that are on-going challenges.

gamelooper
  • 11
  • 1
0

so sweep line algorithm is what you basically need to be aware of, for solving this question.