-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistanceBetweenSegments.cpp
More file actions
82 lines (73 loc) · 2.18 KB
/
DistanceBetweenSegments.cpp
File metadata and controls
82 lines (73 loc) · 2.18 KB
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
#include <iostream>
#include <string>
#include <vector>
#include<cmath>
const double eps = 1e-10;
const size_t output_precision = 10;
struct Point {
double x_;
double y_;
double z_;
Point(double x, double y, double z) : x_(x), y_(y), z_(z) {};
friend Point operator+(const Point& a, const Point& b);
friend Point operator*(const Point& a, double x);
friend Point operator/(const Point& a, double x);
};
Point operator+(const Point& a, const Point& b) {
return Point(a.x_ + b.x_, a.y_ + b.y_, a.z_ + b.z_);
}
Point operator*(const Point& a, const double x) {
return Point(a.x_ * x, a.y_ * x, a.z_ * x);
}
Point operator/(const Point& a, const double x) {
return Point(a.x_ / x, a.y_ / x, a.z_ / x);
}
double DistancePointPoint(Point& a, Point& b) {
return std::sqrt((a.x_ - b.x_) * (a.x_ - b.x_) +
(a.y_ - b.y_) * (a.y_ - b.y_) +
(a.z_ - b.z_) * (a.z_ - b.z_));
}
template <typename Function, typename Set>
double TernarySearch(Point& a, Point& b, Function& f, Set& p) {
// тернарный поиск для нахождения минимума унимодальной функции F
double fa = f(a, p);
double fb = f(b, p);
double fm;
double fn;
Point m(0, 0, 0);
Point n(0, 0, 0);
if (DistancePointPoint(a, b) >= eps) {
m = (b + a * 2) / 3;
n = (a + b * 2) / 3;
fm = f(m, p);
fn = f(n, p);
if (fm > fn) {
return TernarySearch(m, b, f, p);
}
return TernarySearch(a, n, f, p);
}
return fa;
}
double DistancePointSegment(Point& p, std::pair<Point, Point>& segment) {
return TernarySearch(segment.first, segment.second, DistancePointPoint, p);
}
double DistanceSegmentSegment(Point& a, Point& b, Point& c, Point& d) {
std::pair<Point, Point> p = {c, d};
return TernarySearch(a, b, DistancePointSegment, p);
}
int main() {
double x;
double y;
double z;
std::cin >> x >> y >> z;
Point a(x, y, z);
std::cin >> x >> y >> z;
Point b(x, y, z);
std::cin >> x >> y >> z;
Point c(x, y, z);
std::cin >> x >> y >> z;
Point d(x, y, z);
std::cout.precision(output_precision);
std::cout << DistanceSegmentSegment(a, b, c, d) << '\n';
return 0;
}