就是求坐标系内两个矩形的最短距离,这两个矩形一定是分离的,没有相交,没有相切,也没有包含。
没学过ACM几何算法的也可以做。
直接贴代码。
没学过ACM几何算法的也可以做。
直接贴代码。
#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
double dis(double a, double b, double c, double d)
{
return sqrt((a - c) * (a - c) + (b - d) * (b - d));
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
double x1[4], x2[4], y1[4], y2[4];
double mi = 400000;
for (int i = 0; i < 2; i++)
{
scanf("%lf%lf", &x1[i], &y1[i]);
}
for (int i = 0; i < 2; i++)
{
scanf("%lf%lf", &x2[i], &y2[i]);
}
x1[2] = x1[0];
x1[3] = x1[1];
y1[2] = y1[1];
y1[3] = y1[0];
x2[2] = x2[0];
x2[3] = x2[1];
y2[2] = y2[1];
y2[3] = y2[0];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
mi = min(mi, dis(x1[i], y1[i], x2[j], y2[j]));
}
}
if (x2[0] < x2[1])
{
if ((x1[0] > x2[0] && x1[0] < x2[1]) || (x1[1] > x2[0] && x1[1] < x2[1]) || (x2[0] > x1[0] && x2[0] < x1[1]) || (x2[1] > x1[0] && x2[1] < x1[1]))
{
double a = min(fabs(y1[0] - y2[0]), fabs(y1[0] - y2[1]));
double b = min(fabs(y1[1] - y2[0]), fabs(y1[1] - y2[1]));
a = min(a, b);
mi = min(mi, a);
}
}
else
{
if ((x1[0] > x2[1] && x1[0] < x2[0]) || (x1[1] > x2[1] && x1[1] < x2[0]) || (x2[0] > x1[1] && x2[0] < x1[0]) || (x2[1] > x1[1] && x2[1] < x1[0]))
{
double a = min(fabs(y1[0] - y2[0]), fabs(y1[0] - y2[1]));
double b = min(fabs(y1[1] - y2[0]), fabs(y1[1] - y2[1]));
a = min(a, b);
mi = min(mi, a);
}
}
if (y2[0] < y2[1])
{
if ((y1[0] > y2[0] && y1[0] < y2[1]) || (y1[1] > y2[0] && y1[1] < y2[1]) || (y2[0] > y1[0] && y2[0] < y1[1]) || (y2[1] > y1[0] && y2[1] < y1[1]))
{
double a = min(fabs(x1[0] - x2[0]), fabs(x1[0] - x2[1]));
double b = min(fabs(x1[1] - x2[0]), fabs(x1[1] - x2[1]));
a = min(a, b);
mi = min(mi, a);
}
}
else
{
if ((y1[0] > y2[1] && y1[0] < y2[0]) || (y1[1] > y2[1] && y1[1] < y2[0]) || (y2[0] > y1[1] && y2[0] < y1[0]) || (y2[1] > y1[1] && y2[1] < y1[0]))
{
double a = min(fabs(x1[0] - x2[0]), fabs(x1[0] - x2[1]));
double b = min(fabs(x1[1] - x2[0]), fabs(x1[1] - x2[1]));
a = min(a, b);
mi = min(mi, a);
}
}
printf("%.4lf\n", mi);
}
return 0;
}