URAL - 1348 Goat in the Garden 2
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=22321
问题描述:点到线段的最短和最长距离
【最长距离】到两个端点的最大值,好想
【最短距离】首先判断垂足落不落在线段上,可以连成三角形判断底角为锐角,然后点到直线距离;否则,取到两个端点的最小值
思路
点到线段的距离
注意2点,一是点到直线距离时若使用叉乘除以底边的方法要判断底边长度是否为0,否则就除0了!
二者,最后判断minlen 与 maxlen与L的大小关系再确定输出呦~
参考代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<vector>
#include<algorithm>
#include<set>
#include<sstream>
#define eps 1e-9
using namespace std;
typedef long long ll;
const int _max = 2e3 + 10;
int dcmp(double x){
if(fabs(x)<eps) return 0;else return x < 0?-1:1;
}
double l;
struct point{
double x,y;
}c,s,t;//源、汇
double len(point a,point b){//返回两点之间的距离
return hypot(b.x-a.x,b.y-a.y);
}
double dot(point s1,point t1,point s2,point t2){//(t1-s1)点乘(t2-s2)
double x1 = t1.x - s1.x,y1 = t1.y - s1.y;
double x2 = t2.x - s2.x,y2 = t2.y - s2.y;
return x1*x2+y1*y2;
}
double cross(point s1,point t1,point s2,point t2){//(t1-s1)叉乘(t2-s2)
double x1 = t1.x - s1.x,y1 = t1.y - s1.y;
double x2 = t2.x - s2.x,y2 = t2.y - s2.y;
return x1*y2-x2*y1;
}
double dispointtoseg(){//点到线段距离
if(dcmp(dot(s,c,s,t))<0||dcmp(dot(t,s,t,c))<0) return min(len(c,s),len(c,t));
//返回点到直线的距离
if(dcmp(len(s,t)) == 0) return len(s,c);//特判除0的情况
return fabs(cross(s,c,s,t))/len(s,t);
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
#endif // ONLINE_JUDGE
while(scanf("%lf%lf%lf%lf%lf%lf%lf",&s.x,&s.y,&t.x,&t.y,&c.x,&c.y,&l) == 7){
double d1 = dispointtoseg();
double d2 = max(len(c,s),len(c,t));
if(dcmp(d1-l)<=0) puts("0.00"); else printf("%.2f\n",d1-l);
if(dcmp(d2-l)<=0) puts("0.00"); else printf("%.2f\n",d2-l);
//printf("%.2lf\n%.2lf\n",d1-l,d2-l);
}
return 0;
}
- 加粗
Ctrl + B
- 斜体
Ctrl + I
- 引用
Ctrl + Q
- 插入链接
Ctrl + L
- 插入代码
Ctrl + K
- 插入图片
Ctrl + G
- 提升标题
Ctrl + H
- 有序列表
Ctrl + O
- 无序列表
Ctrl + U
- 横线
Ctrl + R
- 撤销
Ctrl + Z
- 重做
Ctrl + Y