UVa 10263 Railway (点到线段的最短距离)

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1204


/*0.016s*/

#include<bits/stdc++.h>
using namespace std;
double eps = 1e-10;

struct P
{
	double x, y;
	P(double x = 0.0, double y = 0.0): x(x), y(y) {}
	bool read()
	{
		return ~scanf("%lf%lf", &x, &y);
	}
	void output()
	{
		printf("%.4f\n%.4f\n", x, y);
	}
	P operator + (P p)
	{
		return P(x + p.x, y + p.y);
	}
	P operator - (P p)
	{
		return P(x - p.x, y - p.y);
	}
	P operator * (double d)
	{
		return P(x * d, y * d);
	}
	P operator / (double d)
	{
		return P(x / d, y / d);
	}
	double dot(P p)
	{
		return x * p.x + y * p.y;
	}
	double det(P p)
	{
		return x * p.y - y * p.x;
	}
} p, ansp;

double mindis;

inline bool onseg(P& p1, P&p2, P& q)
{
	return (p1 - q).dot(p2 - q) < eps;
}

inline P intersection(P& p1, P& p2, P& q1, P q2)
{
	return p1 + (p2 - p1) * ((q2 - q1).det(q1 - p1) / (q2 - q1).det(p2 - p1));
}

void nearest(P& p1, P& p2, P& m)
{
	///如何构造一条垂线:m, m + P(p1.y - p2.y, p2.x - p1.x)
	p = intersection(p1, p2, m, m + P(p1.y - p2.y, p2.x - p1.x));
	if (!onseg(p1, p2, p))
	{
		if ((p2 - p1).dot(p - p1) > eps) p = p2;
		else p = p1;
	}
	double dis = (m - p).dot(m - p);
	if (dis + eps < mindis)
	{
		mindis = dis;
		ansp = p;
	}
}

int main()
{
	int n;
	P m, p1, p2;
	while (m.read())
	{
		scanf("%d", &n);
		mindis = DBL_MAX;
		p2.read();
		while (n--)
		{
			p1 = p2;
			p2.read();
			nearest(p1, p2, m);
		}
		ansp.output();
	}
	return 0;
}

你可能感兴趣的:(C++,ACM,uva,计算几何)