POJ2187 Beauty Contest(旋轉卡殼)
阿新 • • 發佈:2018-11-21
嘟嘟嘟
旋轉卡殼模板題。
首先求出凸包。
然後\(O(n ^ 2)\)的演算法很好想,但那就不叫旋轉卡殼了。
考慮優化:直觀的想是在列舉點的時候,對於第二層迴圈用二分或者三分優化,但實際上兩點距離是不滿足單調性的,見下圖:
對於\(A\)點,\(AB < AC < AD > AE < AF\)。
那怎麼辦呢?
轉換一下思路,如果列舉邊,會發現每一個不在這條邊上的頂點到邊的距離是一個單峰函式!因此就能想到三分這個點,複雜度變成\(O(nlogn)\)。
不過實際上還可以優化,如果逆時針列舉的話,對於邊\(e_i\)的下一條邊\(e_{i + 1}\),會發現到\(e_{i + 1}\)
因此維護兩個指標,一個代表邊,一個代表最遠點。因為這兩個指標最多轉一圈,所以複雜度為\(O(n)\)。
一個優化就是判斷距離的時候,因為底邊是固定的,所以比較距離就是在比較三角形面積。(還能防止掉精度)
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<cstdlib> #include<cctype> #include<vector> #include<stack> #include<queue> using namespace std; #define enter puts("") #define space putchar(' ') #define Mem(a, x) memset(a, x, sizeof(a)) #define rg register typedef long long ll; typedef double db; const int INF = 0x3f3f3f3f; const db eps = 1e-8; const int maxn = 5e4 + 5; inline ll read() { ll ans = 0; char ch = getchar(), last = ' '; while(!isdigit(ch)) last = ch, ch = getchar(); while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); if(last == '-') ans = -ans; return ans; } inline void write(ll x) { if(x < 0) x = -x, putchar('-'); if(x >= 10) write(x / 10); putchar(x % 10 + '0'); } int n; struct Point { int x, y; Point operator - (const Point& oth)const { return (Point){x - oth.x, y - oth.y}; } int operator * (const Point& oth)const { return x * oth.y - oth.x * y; } friend inline int dis(const Point& A) { return A.x * A.x + A.y * A.y; } inline friend void swap(Point& A, Point& B) { swap(A.x, B.x); swap(A.y, B.y); } }p[maxn], S; bool cmp(Point A, Point B) { int s = (A - S) * (B - S); if(s != 0) return s > 0; return dis(A - S) < dis(B - S); } int st[maxn], top = 0; void Graham() { int id = 1; for(int i = 2; i <= n; ++i) if(p[i].x < p[id].x || (p[i].x == p[id].x && p[i].y < p[id].y)) id = i; if(id != 1) swap(p[id], p[1]); S.x = p[1].x, S.y = p[1].y; sort(p + 2, p + n + 1, cmp); st[++top] = 1; for(int i = 2; i <= n; ++i) { while(top > 1 && (p[st[top]] - p[st[top - 1]]) * (p[i] - p[st[top - 1]]) < 0) top--; st[++top] = i; } } int area(Point A, Point B, Point C) { return abs((A - B) * (A - C)); } int nxt(int x) { if(++x > top) x = 1; return x; } int rota() { if(top == 2) return dis(p[st[1]] - p[st[2]]); int ret = 0; st[top + 1] = 1; for(int i = 1, j = 3; i <= top; ++i) { while(nxt(j) != i && area(p[st[i]], p[st[i + 1]], p[st[j]]) <= area(p[st[i]], p[st[i + 1]], p[st[j + 1]])) j = nxt(j); ret = max(ret, dis(p[st[i]] - p[st[j]])); ret = max(ret, dis(p[st[i + 1]] - p[st[j]])); } return ret; } int main() { n = read(); for(int i = 1; i <= n; ++i) p[i].x = read(), p[i].y = read(); Graham(); write(rota()), enter; return 0; }