aoj cgl_7_d 円と直線の交点

CGL_7_D 円と直線の交点

CGL_7_D 円と直線の交点
Feb. 2, 2020, 1:52 p.m.

目次

問題

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D

解説

円と直線の交点を求めるアルゴリズムについては以下リンクを参照.

円と直線の交点

解答

 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
Int N;
double R;
Vector2 C, p1, p2;


Vector2 project(Vector2 start_, Vector2 end_, Vector2 p) {
    Vector2 v = end_ - start_;
    return start_ + v * (v.dot(p - start_) / v.norm());
}

Vector2 unitVec(Vector2 v) {
  return v / v.length();
}

pair<Vector2, Vector2> crossPoints() {
  Vector2 p = project(p1, p2, C);
  Vector2 e = unitVec(p2 - p1);
  double len = sqrt(R*R - (p - C).norm());
  Vector2 x1 = p + e * len;
  Vector2 x2 = p + e * (-len);
  if (fabs(x1.x) < EPS) x1.x = 0.0;
  if (fabs(x1.y) < EPS) x1.y = 0.0;
  if (fabs(x2.x) < EPS) x2.x = 0.0;
  if (fabs(x2.y) < EPS) x2.y = 0.0;
  if (x1 < x2) return make_pair(x1, x2);
  return make_pair(x2, x1);
}

void solve() {
  auto points = crossPoints();
  cout << points.first.x << ' ' << points.first.y << ' ';
  cout << points.second.x << ' ' << points.second.y << endl;
}

void input() {
  cin >> C >> R >> N;
  while (cin >> p1 >> p2) {
    solve();
  }
}

int main() {
  cout.precision(15);
  input();
}