题意: 有两个狗, 按照 多边形跑,不知道两条狗的速度,但是狗是同时出发,同时到达终点的
输出两条狗的 最大相距距离 - 最小相距距离;
思路 : 用物理的相对运动来计算, 每次只计算 两条狗的直线运动, 转折点再额外更新
LRJ 模板大法好 !!!LRJ 模板大法好 !!!!LRJ 模板大法好 !!!!
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int maxn = 100; const double eps = 1e-9; struct Point { double x , y; Point (double x = 0, double y = 0) : x(x),y(y) {} }; typedef Point Vector; int dcmp (double x) { if(fabs(x) < eps) return 0; else return x < 0 ? -1 : 1; } Vector operator + (Vector A, Vector B) { return Vector(A.x+B.x,A.y+B.y); } Vector operator - (Point A, Point 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); } 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 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); } double MAX,MIN; void UpDate(Point P, Point A, Point B) { MIN = min(MIN, DistanceToSegment(P,A,B)); ///当前 和 点 到线段的最小距离 MAX = max(Length(P-A),MAX); MAX = max(Length(P-B),MAX); } Point Pa[maxn], Pb[maxn]; int main() { int t; scanf("%d",&t); for(int kase = 1; kase <= t; kase++) { int A, B; scanf("%d %d",&A,&B); for(int i = 0; i < A; ++i) cin >> Pa[i].x >> Pa[i].y; for(int i = 0; i < B; ++i) cin >> Pb[i].x >> Pb[i].y; double LenA = 0, LenB = 0; for(int i = 0; i < A-1; ++i) LenA += Length(Pa[i] - Pa[i+1]); for(int i = 0; i < B-1; ++i) LenB += Length(Pb[i] - Pb[i+1]); MAX = -1e9; MIN = 1e9; int sa = 0, sb = 0; ///下一个转折点 Point Na = Pa[0], Nb = Pb[0]; /// 起始位置 while(sa < A-1 && sb < B-1) { double La = Length(Pa[sa+1] - Na); /// a 当前到下一个转折点的长度 double Lb = Length(Pb[sb+1] - Nb); /// b ... double t = min(La / LenA, Lb / LenB); /// 运动的时间 Vector Va = (Pa[sa+1] - Na) / La * t * LenA;/// a 的位移量 Vector Vb = (Pb[sb+1] - Nb) / Lb * t * LenB;/// b 的位移量 UpDate(Na,Nb,Nb+Vb-Va); /// B相对A 的运动就是 NB + Vb - Va; Na = Na + Va; /// 更新 a 的当前点 Nb = Nb + Vb; if(Na == Pa[sa+1]) sa++; ///如果到了转折点, sa 下一个转折点更新 if(Nb == Pb[sb+1]) sb++; } printf("Case %d: %.0lf\n",kase, MAX - MIN); } return 0; }
时间: 2024-10-20 15:00:41