二分三分 POJ3301 三分
Texas Trip
Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 6388 | Accepted: 1986 |
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
求最小能覆蓋過所給點的正方形面積,我們可以想到,如果正方形區域是正的嗎,那麼y的最大最小值之差與x的最大最小值之差中大的那個就是最小正方形面積。
然而,正方形可以旋轉。
但我們發現,旋轉正方形就很難判定問題得到結果,那我們就轉換一下,根據相對性,可以想成旋轉座標;旋轉座標不好計算旋轉後的座標,那我們再轉換一下,可以想成旋轉座標系。我們可以得到座標軸旋轉t角度的橫縱座標公式:
x' = x*cost + y*sint
y' = y*cost - x*sint
現在問題又來了,我們怎樣得到正方形區域面積最小的角度?
正方形面積隨旋轉角的變化並不是一個單調的關係,我們想到中間會有最小值的存在,所以三分角度。
程式碼如下:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define PI acos(-1.0)
using namespace std;
const int maxn=30;
const int maxp=500,minp=-500;
const double eps=1e-8;
int n;
struct point{
int x,y;
}p[maxn+10];
double cal(double t)
{
double x,y,xm,xs,ym,ys;
xm=ym=minp;
xs=ys=maxp;
for(int i=0;i<n;++i){
x=p[i].x*cos(t)+p[i].y*sin(t);
y=p[i].y*cos(t)-p[i].x*sin(t);
if(x>xm) xm=x;
if(x<xs) xs=x;
if(y>ym) ym=y;
if(y<ys) ys=y;
}
double sa=max((xm-xs),(ym-ys));
return sa*sa;
}
int main()
{
int t;
int xm,xs,ym,ys;
scanf("%d",&t);
while(t--){
xm=ym=minp;
xs=ys=maxp;
memset(p,0,sizeof(p));
scanf("%d",&n);
for(int i=0;i<n;++i){
scanf("%d%d",&p[i].x,&p[i].y);
// if(p[i].x>xm) xm=p[i].x;
// if(p[i].x<xs) xs=p[i].x;
// if(p[i].y>ym) ym=p[i].y;
// if(p[i].x<ys) ys=p[i].y;
}
double left=0,right=PI/2,midl,midr;
double cmidl,cmidr;
while(right-left>eps){
midl=(left+right)/2;
midr=(midl+right)/2;
cmidl=cal(midl);
cmidr=cal(midr);//printf("c:%.2f %.2f\n",cmidl,cmidr);
if(cmidl<cmidr)
right=midr;
else
left=midl;
}
printf("%.2f\n",cmidl);
}
return 0;
}