0%

POJ 1127

《挑战程序设计竞赛》里面扣了点东西(P250)

Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#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);
}
};

int n;
const int MAX_N = 1000;
P p[MAX_N], q[MAX_N];
int m;
int a[MAX_N], b[MAX_N];

bool g[MAX_N][MAX_N];

bool on_seg(P p1, P p2, P q)
{
return (p1 - q).det(p2 - q) == 0 && (p1 - q).dot(p2 - q) <= 0;
}

P intersection(P p1, P p2, P q1, P q2)
{
return p1 + (p2 - p1) * ((q2 - q1).det(q1 - p1) / (q2 - q1).det(p2 - p1));
}


void solve()
{
for (int i = 0; i < n; ++i)
{
g[i][i] = true;
for (int j = 0; 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)
{
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 i = 0; i < m; ++i)
{
puts(g[a[i] - 1][b[i] - 1] ? "CONNECTED" : "NOT CONNECTED");
}
}


int main()
{
//freopen("data.txt", "r", stdin);
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> p[i].x >> p[i].y;
}
for (int i = 0; i < n; ++i)
{
cin >> q[i].x >> q[i].y;
}
cin >> m;
for (int j = 0; j < m; ++j)
{
cin >> a[j] >> b[j];
}
solve();
return 0;
}

里面引入的向量概念,使用向量有关的计算来判断两直线是否相交(on_seg),算是和几何的一个应用吧。

测试数据

输入

1
2
3
4
5
4
0 4 0 1 1 2 1 0
4 1 2 3 3 4 2 1
4
1 2 1 4 2 3 2 4

输出

1
2
3
4
CONNECTED
NOT CONNECTED
CONNECTED
NOT CONNECTED