[POJ 3301] Texas Trip【三分查找】
Problem:
Time Limit: 1000MS | Memory Limit: 65536K |
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
Source
Solution:
可以证明正方形边长关于倾斜角度的函数是开口向上的凸函数,可以用三分法求解。
在 [0, π) 上三分倾斜角度 θ。
检验时枚举每2个点,计算经过这2个点且与 x 轴成角度 θ 和 θ + π / 2 的平行线间距离:
- dis(θ) = |Δy cosθ - Δx sinθ|
- dis(θ + π / 2) = |Δy sinθ + Δx cosθ|
Code: O(Tn2log3(π/ε)) [204K, 32MS]
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<algorithm> #define eps 1e-8 using namespace std; const double PI = acos(-1.0); inline int dsgn(double x){ if(fabs(x) <= eps) return 0; return x < 0 ? -1 : 1; } inline double sqr(double x) {return x * x;} int T, n; struct Point{ double x, y; Point() {} Point(double x, double y): x(x), y(y) {} } p[35]; inline double minsquare(const double &theta){ double minlen = 0; for(register int i = 1; i < n; i++) for(register int j = i + 1; j <= n; j++){ minlen = max(minlen, fabs((p[i].y - p[j].y) * cos(theta) - (p[i].x - p[j].x) * sin(theta))); minlen = max(minlen, fabs((p[i].y - p[j].y) * sin(theta) + (p[i].x - p[j].x) * cos(theta))); } return minlen; } int main(){ scanf("%d", &T); while(T--){ scanf("%d", &n); for(register int i = 1; i <= n; i++) scanf("%lf%lf", &p[i].x, &p[i].y); double lft = 0, rt = PI; while(dsgn(lft - rt) < 0){ double lmid = lft + (rt - lft) / 3, rmid = rt - (rt - lft) / 3; if(dsgn(minsquare(lmid) - minsquare(rmid)) > 0) lft = lmid; else rt = rmid; } printf("%.2f\n", sqr(minsquare(lft))); } return 0; }
发表评论