有N線段可以是水平或垂直。現在我需要找出每個線段的交點總數和交點總數。 N可以高達。我試着檢查每一對線。答案是正確的,但我需要減少它的時間。減少查找N線交點所需的時間
這裏是我的代碼:
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;
}
有人能幫助我減少這個程序的時間複雜度?
如果它們是水平或垂直的,那麼檢查交點比任意線更容易(如在你的方法中)。此外,從x/y座標開始排序。然後你知道可能的交叉點必須在哪個區域。更復雜的方法是使用分段樹或間隔樹。 –
同一位老師還是比賽? http://stackoverflow.com/questions/40570886/c-modified-line-segment-intersection – MBo
請參閱[用C#實現Hoey Shamos算法](http://stackoverflow.com/q/18512815/2521214)兩個答案.. – Spektre