poj3301–Texas Trip(最小正方形覆盖)
Texas Trip
Description
After a day trip with his friend Dick, Harry noticed a strange pattern of tiny holes in the door of his SUV. The local American Tire store sells fiberglass patching material only in square sheets. What is the smallest patch that Harry needs to fix his door?
Assume that the holes are points on the integer lattice in the plane. Your job is to find the area of the smallest square that will cover all the holes.
Input
The first line of input contains a single integer T expressed in decimal with no leading zeroes, denoting the number of test cases to follow. The subsequent lines of input describe the test cases.
Each test case begins with a single line, containing a single integer n expressed in decimal with no leading zeroes, the number of points to follow; each of the following n lines contains two integers x and y, both expressed in decimal with no leading zeroes, giving the coordinates of one of your points.
You are guaranteed that T ≤ 30 and that no data set contains more than 30 points. All points in each data set will be no more than 500 units away from (0,0).
Output
Print, on a single line with two decimal places of precision, the area of the smallest square containing all of your points.
Sample Input
2 4 -1 -1 1 -1 1 1 -1 1 4 10 1 10 -1 -10 1 -10 -1
Sample Output
4.00
242.00
题目大意:给出n个点的坐标,现在要求一个正方形,完全包围n个点,并且正方形面积最小,求最小的正方形面积。
如果面积随角度变化是单峰的函数,那么自然就可以想到是三分,按照题目要求求正方形最小的面积,如果正方形是平行于x轴的,那么正方形面积是x的最大距离*y的最大的距离。然后旋转正方形,在0到90度内总会找到一个正方形面积的最小值,,,但是旋转正方形比较麻烦,我们可以考虑旋转坐标系,将做坐标系旋转0到90度,按旋转的角度重新计算各点的坐标,然后找出x的差和y的差,计算面积。
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<stack>
#include<cstdio>
#include<map>
#include<set>
#include<string>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define mem(x) memset(x,0,sizeof(x))
#define PI 3.1415926
struct point
{
int x,y;
}p[40];
int n;
double f(double a){
double maxx=-inf,minx=inf,maxy=-inf,miny=inf;
for (int i = 0; i < n; ++i)
{
maxx = max(maxx,p[i].x*cos(a)-p[i].y*sin(a));
maxy = max(maxy,p[i].x*sin(a)+p[i].y*cos(a));
minx = min(minx,p[i].x*cos(a)-p[i].y*sin(a));
miny = min(miny,p[i].x*sin(a)+p[i].y*cos(a));
}
return max((maxx-minx),(maxy-miny));
}
int main(int argc, char const *argv[])
{
int t;
cin>>t;
while(t--){
cin>>n;
for (int i = 0; i < n; ++i)
{
cin>>p[i].x>>p[i].y;
}
double l=0,r=PI/2.0;
while(r-l>0.00001){
double lmid,rmid;
lmid = l + (r-l)/3.0;
rmid = r - (r-l)/3.0;
if(f(lmid)>f(rmid)) l=lmid;
else r=rmid;
}
double ans=f(r)*f(r);
printf("%.2lf",ans);
}
return 0;
}