1. 程式人生 > >Codeforces 1079D Barcelonian Distance(計算幾何)

Codeforces 1079D Barcelonian Distance(計算幾何)

pen clu sin ces img 鏈接 sta show 直線

題目鏈接:Barcelonian Distance

題意:給定方格坐標,方格坐標上有兩個點A,B和一條直線。規定:直線上沿直線走,否則沿方格走。求A到B的最短距離。

題解:通過直線到達的:A、B兩點都有兩種方式到直線上,最多4種情況,每種情況求出A、B點到直線的距離和直線上新的兩點間距離,取4種情況中最優的。

不通過直線到達:$abs(x1-x2)+abs(y1-y2)$,最後與通過直線到達的最優情況比較,得到最優解。

技術分享圖片
 1 #include <cmath>
 2 #include <cstdio>
 3 #include <algorithm>
 4
using namespace std; 5 6 double a,b,c,ans; 7 double x1,y1,x2,y2; 8 9 double calx(double y){ 10 return (-c-b*y)/a; 11 } 12 13 double caly(double x){ 14 return (-c-a*x)/b; 15 } 16 17 double cal1(double x1,double x2){ 18 double X1,X2,Y1,Y2; 19 double res=0; 20 X1=x1;Y1=caly(x1);
21 res+=abs(Y1-y1); 22 X2=x2;Y2=caly(x2); 23 res+=abs(Y2-y2); 24 res+=sqrt((X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2)); 25 return res; 26 } 27 28 double cal2(double x1,double y2){ 29 double X1,X2,Y1,Y2; 30 double res=0; 31 X1=x1;Y1=caly(x1); 32 res+=abs(Y1-y1); 33
X2=calx(y2);Y2=y2; 34 res+=abs(X2-x2); 35 res+=sqrt((X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2)); 36 return res; 37 } 38 39 double cal3(double y1,double x2){ 40 double X1,X2,Y1,Y2; 41 double res=0; 42 X1=calx(y1);Y1=y1; 43 res+=abs(X1-x1); 44 X2=x2;Y2=caly(x2); 45 res+=abs(Y2-y2); 46 res+=sqrt((X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2)); 47 return res; 48 } 49 50 51 double cal4(double y1,double y2){ 52 double X1,X2,Y1,Y2; 53 double res=0; 54 X1=calx(y1);Y1=y1; 55 res+=abs(X1-x1); 56 X2=calx(y2);Y2=y2; 57 res+=abs(X2-x2); 58 res+=sqrt((X1-X2)*(X1-X2)+(Y1-Y2)*(Y1-Y2)); 59 return res; 60 } 61 62 int main(){ 63 scanf("%lf%lf%lf",&a,&b,&c); 64 scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2); 65 double ans=abs(x1-x2)+abs(y1-y2); 66 if(a==0||b==0){ 67 printf("%.10f\n",abs(x1-x2)+abs(y1-y2)); 68 return 0; 69 } 70 ans=min(ans,cal1(x1,x2)); 71 ans=min(ans,cal2(x1,y2)); 72 ans=min(ans,cal3(y1,x2)); 73 ans=min(ans,cal4(y1,y2)); 74 printf("%.10f\n",ans); 75 return 0; 76 }
View Code

Codeforces 1079D Barcelonian Distance(計算幾何)