題意:給定兩條狗的行走路線,一直兩條狗同時出發同時到達,問路途中的最遠和最近距離
思路:把每一段路程,當成相對運動,這樣就是一只狗靜止,一只在動,最小值相當於求點到線段距離,最大值為點到線段兩端距離
代碼:
#include#include #include #include 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; }