Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5896 | Accepted: 1824 |
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
题意:给定一堆点,求包含所有点的最小正方形
解答:如图,假设出这样一个最小矩形,包含了所有点。
那么我们如何来求面积呢?我们只要知道了边长就能求出面积,这样斜着肯定不好求,但是如果是边长与坐标轴平行我们一定能求出来,边长=max(Dx,Dy),所以我们把所有点旋转一个角度,转多了面积过大,转少了也过大,是个单峰函数,所以三分旋转角度。
旋转公式:y'=r*sin(angle+a)
x'=r*cos(angle+a)
展开再把想x,y代入。
得 : x'=x*cos(angle)-y*sin(angle);
y'=y*cos(angle)+x*sin(angle);
顺时针,逆时针不影响,90度就可以了
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<math.h>
#include<iomanip>
using namespace std;
const double pi=3.1415926;
const double eps=1e-8;
double x[35],y[35];
int n;
double ans;
double check(double angle)
{
double x1[35],y1[35];
for(int i=1;i<=n;i++)
{
x1[i]=x[i]*cos(angle)+y[i]*sin(angle);
y1[i]=y[i]*cos(angle)-x[i]*sin(angle);
}
sort(x1+1,x1+1+n);
sort(y1+1,y1+1+n);
return ans=max((x1[n]-x1[1]),y1[n]-y1[1]);
}
int main()
{
ios::sync_with_stdio(false);
//freopen("text.txt", "r", stdin);
int t;
cin>>t;
while(t--)
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x[i]>>y[i];
}
double mid,mmid,low=0,high=pi/2;
while(high-low>=eps)
{
mid=(low+high)/2.0;
mmid=(low+mid)/2.0;
if(check(mid)>check(mmid))high=mid;
else low=mmid;
}
cout<<setprecision(2)<<fixed<<ans*ans<<endl;
}
return 0;
}