15,919,479 members
1.00/5 (1 vote)
See more:
```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
!<=Q<= 100000

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

What I have tried:

I dont know how to approach it .I thought kd tree may help.But I dont know how to use it for line segment.
Posted
Updated 14-Mar-20 22:57pm

## Solution 1

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

The approach is brut force, test very single segment against every horizontal segment.
Apply the KISS method a list of N-1 segments, a list of Q horizontal segments, nothing fancy.
Complexity is (N-1)*Q
Quote:
I thought kd tree may help.

To use a method with this or with that, you need to have an idea of how it will help before.
When you search the correct algorithm to solve a problem:
- first choose brute force and evaluate the workload.
- Search an improves method and evaluate new workload, keep if workload reduction.
- try to improve further with another method or refinement.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Pete O'Hanlon 80 OriginalGriff 70 Wendelius 40 Patrice T 40 Maciej Los 30
 Pete O'Hanlon 850 OriginalGriff 711 Dave Kreskowiak 455 Richard MacCutchan 320 merano99 280

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900