CF1032D Barcelonian Distance

算是自己切的第一道计算几何了,写篇题解记录一下。

Solution

首先,我们发现,如果 ((x_1,y_1))((x_2,y_2)) 是经过 (ax+by+c=0) 的,那么一定是从 (x=x_1)(y=y_1)(x=x_2)(y=y_2) ,所以我们可以枚举这四种路径和不经过 (ax+by+c=0) 的路径,取最小值即可。

然后可以用初中学过的方法求出 (ax+by+c=0) 和那四条直线的交点: ((x_3,y_3)=(x_1,frac {-a imes x_1-c}b),(x_4,y_4)=(frac {-b imes y_1-c}a,y_1),(x_5,y_5)=(x_2,frac {-a imes x_2-c}b),(x_6,y_6)=(frac {-b imes y_2-c}a,y_2))

然后再用初中学过的勾股定理算出路径长

然后算就完了!奥力给

小细节:记得用 (fabs) ,不然样例都过不去。

代码

#include<cmath>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<iostream>

using namespace std;
double a,b,c,x[10],y[10],ans;

int main(){
    ios::sync_with_stdio(false);
    cin>>a>>b>>c>>x[1]>>y[1]>>x[2]>>y[2];
    ans=fabs(x[1]-x[2])+fabs(y[1]-y[2]);
    x[3]=x[1];
    y[3]=(-a*x[1]-c)/b;
    x[4]=(-b*y[1]-c)/a;
    y[4]=y[1];
    x[5]=x[2];
    y[5]=(-a*x[2]-c)/b;
    x[6]=(-b*y[2]-c)/a;
    y[6]=y[2];
    for(int i=3;i<=4;i++)
        for(int j=5;j<=6;j++){
            ans=min(ans,fabs(x[1]-x[i])+fabs(y[1]-y[i])+
                    sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]))+
                    fabs(x[2]-x[j])+fabs(y[2]-y[j]));
        }
    cout<<setprecision(12)<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/jasony/p/13817551.html