fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. class Point {
  6. public:
  7. double x, y;
  8. Point() { }
  9. Point(double _x, double _y) {
  10. x = _x;
  11. y = _y;
  12. }
  13. void getData() {
  14. cin >> x >> y;
  15. }
  16. // kiểm tra điểm này có nằm giữa 2 điểm A và B không
  17. bool isMiddle(const Point &A, const Point &B) {
  18. int ok = 0;
  19. ok += (A.x <= x && x <= B.x) || (A.x >= x && x >= B.x);
  20. ok += (A.y <= y && y <= B.y) || (A.y >= y && y >= B.y);
  21. return ok == 2;
  22. }
  23. };
  24.  
  25. class Line {
  26. private:
  27. // hệ số của đường thẳng ax + by = c
  28. double a, b, c;
  29. public:
  30. Line(const Point &A, const Point &B) {
  31. if (A.x == B.x) {
  32. a = 1;
  33. b = 0;
  34. } else {
  35. a = (B.y - A.y) / (A.x - B.x);
  36. b = 1;
  37. }
  38. c = a * A.x + b * A.y;
  39. }
  40. pair<int, Point> getIntersection(const Line &other) {
  41. // định thức Cramer
  42. double d = a * other.b - b * other.a;
  43. double dx = c * other.b - b * other.c;
  44. double dy = a * other.c - c * other.a;
  45. if (d) {
  46. // 2 đường cắt nhau -> 1 giao điểm
  47. return {1, Point(dx/d, dy/d)};
  48. }
  49. if (dx || dy) {
  50. // 2 đường thẳng song song -> 0 giao điểm
  51. return {0, Point()};
  52. }
  53. // 2 đường trùng nhau -> vô số giao điểm
  54. return {2, Point()};
  55. }
  56. };
  57.  
  58. int main() {
  59. cout << fixed << setprecision(2);
  60. Point A, B, C, D;
  61. A.getData();
  62. B.getData();
  63. C.getData();
  64. D.getData();
  65. Line m(A, B);
  66. Line n(C, D);
  67. auto [k, E] = m.getIntersection(n);
  68. if (k == 0) {
  69. cout << "NO";
  70. } else if (k == 1) {
  71. if (E.isMiddle(A, B) && E.isMiddle(C, D)) {
  72. cout << E.x << ' ' << E.y;
  73. } else {
  74. cout << "NO";
  75. }
  76. } else {
  77. if (A.x > B.x) {
  78. swap(A, B);
  79. }
  80. if (C.x > D.x) {
  81. swap(C, D);
  82. }
  83. if (A.x > C.x) {
  84. swap(A, C);
  85. swap(B, D);
  86. }
  87. if (B.x < C.x) {
  88. cout << "NO";
  89. } else if (B.x > C.x) {
  90. cout << "MANY";
  91. } else {
  92. cout << B.x << ' ' << B.y;
  93. }
  94. }
  95. }
Success #stdin #stdout 0.01s 5280KB
stdin
1 0
0 1
1 1
0 0
stdout
0.50 0.50