题目的意思:给你N条木棍的两段的坐标,问 a 木棍与 b 木棍是否相连。间接的相连也算。
判断点q 是否在线段p1p2上,只要利用外积是否有(p1 - q) * (p2 - q) = 0来判断是否在直线p1p2,再利用内积根据是否有(p1 - q) * (p2 - q) <= 0来判断q是否落在线段p1p2之间。
要求两直线的交点,通过变量t 将直线p1p2上的点表示为p1 + t(p2 - p1),交点又在直线q1q2上,所以:
(q2 - q1) * (p1 + t (p2 - p1) - q1) = 0;
还要判断平行的情况。
下面的是AC的代码:
#include <iostream>
#include <cmath>
using namespace std;
double EPS = 1e-10;
//加法精度误差
double add(double a, double b)
{
if(abs(a + b) < EPS * (abs(a) + abs(b)))
return 0;
return a + b;
}
struct P
{
double x, y;
P(){}
P(double x, double y) : x(x), y(y)
{
}
P operator + (P p)
{
return P(add(x, p.x), add(y, p.y));
}
P operator - (P p)
{
return P(add(x, -p.x), add(y, -p.y));
}
P operator * (double d)
{
return P(x * d, y * d);
}
double dot(P p) //内积
{
return add(x * p.x, y * p.y);
}
double det(P p) //外积
{
return add(x * p.y, -y * p.x);
}
};
//判断点q是否在线段p1p2上
bool on_seg(P p1, P p2, P q)
{
return (p1 - q).det(p2 - q) == 0 && (p1 - q).dot(p2 - q) <= 0;
}
//计算直接p1p2与直线q1q2的交点
P intersection(P p1, P p2, P q1, P q2)
{
return p1 + (p2 - p1) * ((q2 - q1).det(q1 - p1) / (q2 - q1).det(p2 - p1));
}
//输入的数据
int n;
P p[15], q[15];
int m;
int a[10005], b[10005];
//关系图
bool g[15][15];
void solve()
{
for(int i = 0; i < n; i++)
{
g[i][i] = true;
for(int j = 0; j < i; j++)
{ //判断木棍i和j是否有交点
if((p[i] - q[i]).det(p[j] - q[j]) == 0)
{ //平行
g[i][j] = g[j][i] = on_seg(p[i], q[i], p[j]) |
on_seg(p[i], q[i], q[j]) |
on_seg(p[j], q[j], p[i]) |
on_seg(p[j], q[j], q[i]);
}
else //不平行
{
P r = intersection(p[i], q[i], p[j], q[j]);
g[i][j] = g[j][i] = on_seg(p[i], q[i], r) && on_seg(p[j], q[j], r);
}
}
}
for(int k = 0; k < n; k++) //Floyd 算法判断任意两点是否相连
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
g[i][j] |= g[i][k] && g[k][j];
}
}
for(int e = 0; e < m; e++)
{
puts(g[a[e] - 1][b[e] - 1] ? "CONNECTED" : "NOT CONNECTED");
}
}
int main()
{
int x, y;
// freopen("1127.txt", "r", stdin);
while(cin >> n && n) //输入
{
for(int i = 0; i < n; i++)
cin >> p[i].x >> p[i].y >> q[i].x >> q[i].y;
int j = 0;
while(cin >> x >> y)
{
if(x == 0 && y == 0)
break;
a[j] = x; b[j] = y;
j++;
}
m = j;
solve();
}
return 0;
}