Reduce the time taken to find the intersection of N lines

There are N line segments that are either horizontal or vertical. Now I need to find out the total number of intersections and the total number of intersections per line segment. N can go up to 100000. I tried to check every pair of lines. The answer is correct, but I need to reduce the time spent on it.

Here is my code:

using namespace std;

typedef struct Point
{
     long long int x;
     long long int y;
} ;


bool fun(Point p0, Point p1, Point p2, Point p3)
{
    double s1_x, s1_y, s2_x, s2_y;
    s1_x = p1.x - p0.x;     s1_y = p1.y - p0.y;
    s2_x = p3.x - p2.x;     s2_y = p3.y - p2.y;

    double s, t;
    s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
    t = ( s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        return 1; // Collision detected
    }

    return 0; // No collision
}


int main()
{
     long long int n // number of line segments;

     Point p[n],q[n]; // to store end points of line segments

    for( long long int i=0;i<n;i++)
    {

// line segments is defined by 2 points P(x1,y1) and Q(x2,y2)
        p[i].x=x1;
        p[i].y=y1;
        q[i].x=x2;
        q[i].y=y2;
    }

    for( long long int i=0;i<n-1;i++)
    {
        for( long long int j=i+1;j<n;j++)
        {
            if(fun(p[i],q[i],p[j],q[j]))
               count++;
        }

    }

    return 0;
}

Can someone help me reduce the time complexity of this program?

+4
source share
1 answer

It uses the O (n log n) -time algorithm, which uses a sweep line with the Fenwick tree.

Step 0: remapping coordinates

x- 0..n-1, . y-. , .

1:

. .

y. , . . , . , , . ( , + , - , ). (. , , .)

2:

, .

. , , , . y, y . , y . , y . , , , , . , , y ( ).

, . .

+1

Source: https://habr.com/ru/post/1660595/


All Articles