题意:给定两条狗的行走路线,一直两条狗同时出发同时到达,问路途中的最远和最近距离
思路:把每一段路程,当成相对运动,这样就是一只狗静止,一只在动,最小值相当于求点到线段距离,最大值为点到线段两端距离
代码:
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; struct Point { double x, y; Point() {} Point(double x, double y) { this->x = x; this->y = y; } void read() { scanf("%lf%lf", &x, &y); } }; typedef Point Vector; Vector operator + (Vector A, Vector B) { return Vector(A.x + B.x, A.y + B.y); } Vector operator - (Vector A, Vector B) { return Vector(A.x - B.x, A.y - B.y); } Vector operator * (Vector A, double p) { return Vector(A.x * p, A.y * p); } Vector operator / (Vector A, double p) { return Vector(A.x / p, A.y / p); } bool operator < (const Point& a, const Point& b) { return a.x < b.x || (a.x == b.x && a.y < b.y); } const double eps = 1e-8; int dcmp(double x) { if (fabs(x) < eps) return 0; else return x < 0 ? -1 : 1; } bool operator == (const Point& a, const Point& b) { return dcmp(a.x - b.x) == 0 && dcmp(a.y - b.y) == 0; } double Dot(Vector A, Vector B) {return A.x * B.x + A.y * B.y;} //点积 double Length(Vector A) {return sqrt(Dot(A, A));} //向量的模 double Angle(Vector A, Vector B) {return acos(Dot(A, B) / Length(A) / Length(B));} //向量夹角 double Cross(Vector A, Vector B) {return A.x * B.y - A.y * B.x;} //叉积 double dist(Point a, Point b) { Vector tmp = a - b; return sqrt(tmp.x * tmp.x + tmp.y * tmp.y); } double DistanceToSegment(Point P, Point A, Point B) { if (A == B) return Length(P - A); Vector v1 = B - A, v2 = P - A, v3 = P - B; if (dcmp(Dot(v1, v2)) < 0) return Length(v2); else if (dcmp(Dot(v1, v3)) > 0) return Length(v3); else return fabs(Cross(v1, v2)) / Length(v1); } const int N = 55; int T, n, m; Point a[N], b[N]; double Min, Max; void gao(Point A, Point B, Point C) { Min = min(Min, DistanceToSegment(A, B, C)); Max = max(Max, dist(A, B)); Max = max(Max, dist(A, C)); } int main() { int cas = 0; scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) a[i].read(); for (int i = 0; i < m; i++) b[i].read(); double va = 0, vb = 0; Point pa = a[0], pb = b[0]; for (int i = 0; i < n - 1; i++) va += dist(a[i + 1], a[i]); for (int i = 0; i < m - 1; i++) vb += dist(b[i + 1], b[i]); int ua = 0, ub = 0; Min = 1e20, Max = -1e20; while (ua < n - 1 && ub < m - 1) { double sa = dist(pa, a[ua + 1]); double sb = dist(pb, b[ub + 1]); double t = min(sa / va, sb / vb); Vector Va = (a[ua + 1] - pa) / sa * t * va; Vector Vb = (b[ub + 1] - pb) / sb * t * vb; gao(pa, pb, pb - Va + Vb); pa = pa + Va; pb = pb + Vb; if (pa == a[ua + 1]) ua++; if (pb == b[ub + 1]) ub++; } printf("Case %d: %.0lf\n", ++cas, Max - Min); } return 0; }
UVA 11796 - Dog Distance(计算几何)
原文:http://blog.csdn.net/accelerator_/article/details/44567507