BOJ 17387: 선분 교차 2

https://www.acmicpc.net/problem/17387

  • 3월동안 210문제 풀기 (3/210)
  • 선분 교차 판단 방법을 배우는 문제
    • 한 선분의 양끝점과 나머지 선분의 한 점을 이어서 CCW를 두개 만든 뒤,
    • 두 CCw의 부호가 반대임을 확인하면 됨
    • 둘중에 하나가 0이라면 한 끝점이 만나는 경우
    • 둘 다 0이라면 한 직선위에 둘다 있는 경우이다.
    • 이 경우에는 vector a,b / c,d에 대해서 x,y 좌표 모두 a < d 또는 c < b를 만족하는지 확인해봐야한다.
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
#include <bits/stdc++.h>
using namespace std;

const double EPS = 1e-9;
struct Vector {
  double x, y;

  Vector() {
    this->x = 0, this->y = 0;
  }

  Vector(int x, int y) {
    this->x = x, this->y = y;
  }

  Vector(const Vector& v1) {
    x = v1.x, y =v1.y;
  }

  Vector(const Vector& v1, const Vector& v2) {
    x = v2.x - v1.x, y = v2.y - v1.y;
  }

  Vector& operator+=(const Vector &other) {
    x += other.x;
    y += other.y;
    return *this;
  }

  Vector& operator-=(const Vector &other) {
    x -= other.x;
    y -= other.y;
    return *this;
  }

  Vector& operator*=(const double C) {
    x *= C;
    y *= C;
    return *this;
  }

  Vector& operator/=(const double C) {
    x /= C;
    y /= C;
    return *this;
  }

  Vector operator+(const Vector &other) const {
    return Vector(*this) += other;
  }

  Vector operator-(const Vector &other) const {
    return Vector(*this) -= other;
  }

  Vector operator*(const double C) const {
    return Vector(*this) *= C;
  }

  Vector operator/(const double C) const {
    return Vector(*this) /= C;
  }
};

double cross(Vector v1, Vector v2) {
  return v1.x * v2.y - v1.y * v2.x;
}

double ccw(Vector va, Vector vb) {
  double v = cross(va, vb);
  if(abs(v) < EPS) return 0;
  if(v > 0) return 1;
  if(v < 0) return -1;
}

double ccw(Vector vr, Vector va, Vector vb) {
  return ccw(va - vr, vb - vr);
}

bool project(double x1, double x2, double x3, double x4) {
  if(x1 > x2) swap(x1,x2);
  if(x3 > x4) swap(x3,x4);
  return max(x1,x3) <= min(x2, x4);
}

int main() {
  Vector v1, v2, v3, v4;
  cin >> v1.x >> v1.y;
  cin >> v2.x >> v2.y;
  cin >> v3.x >> v3.y;
  cin >> v4.x >> v4.y;

  double v1Root = ccw(v1, v2, v3) * ccw(v1, v2, v4);
  double v3Root = ccw(v3, v4, v1) * ccw(v3, v4, v2);
  if (v1Root == 0 && v3Root == 0) {
    if(project(v1.x, v2.x, v3.x, v4.x) && project(v1.y, v2.y, v3.y, v4.y))
      printf("1");
    else printf("0");
    return 0;
  }
  if (v1Root <= 0 && v3Root <= 0) printf("1");
  else printf("0");
}