poj2187(凸包)

/*
translation:
	給出n個點的位置,計算出距離最遠的一對點的距離。
solution:
	求凸包然後枚舉凸包上的點計算即可。
note:
	* 旋轉卡殼法更加高效。
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;
const int maxn = 50000 + 5;
const double EPS = 1e-10;

double add(double a, double b)
{
    if(abs(a + b) < EPS * (abs(a) + abs(b)))    return 0;
    return a + b;
}

struct P
{
    double x, y;
    P(){}
    P(double x_, double y_):x(x_),y(y_){}

    bool operator < (const P& rhs) const {
        return x < rhs.x || (x == rhs.x && y < rhs.y);
    }

    P operator + (P p) {
        return P(add(x, p.x), add(y, p.y));
    }
    P operator - (P p) {
        return P(add(x, -p.x), add(y, -p.y));
    }
    P operator * (double d) {
        return P(x * d, y * d);
    }
    double dot(P p) {    //內積
        return add(x * p.x, y * p.y);
    }
    double det(P p) {   //外積
        return add(x * p.y, -y * p.x);
    }
} ps[maxn];
int n;

double dist(P p, P q)
{
    return (p - q).dot(p - q);
}

vector<P> graham()
{
    sort(ps, ps + n);
    int k = 0;
    vector<P> res;
    res.resize(n * 2);

    for(int i = 0; i < n; i++) {
        while(k > 1 && (res[k-1] - res[k-2]).det(ps[i] - res[k-1]) <= 0)    k--;
        res[k++] = ps[i];
    }

    for(int i = n - 2, t = k; i >= 0; i--) {
        while(k > t && (res[k-1] - res[k-2]).det(ps[i] - res[k-1]) <= 0)    k--;
        res[k++] = ps[i];
    }
    res.resize(k - 1);
    return res;
}

bool cmp(const P& a, const P& b)
{
    if(a.x != b.x)  return a.x < b.x;
    return a.y < b.y;
}

double solve()
{
    vector<P> tmp = graham();
    if(tmp.size() == 2) {
        return dist(tmp[0], tmp[1]);
    }

    int i = 0, j = 0;

    for(int k = 0; k < n; k++) {
        if(!cmp(tmp[i], tmp[k]))    i = k;
        if(cmp(tmp[j], tmp[k]))     j = k;
    }
    double res = 0;
    int si = i, sj = j;
    while(i != sj || j != si) {
        res = max(res, dist(tmp[i], tmp[j]));
        if((tmp[(i + 1) % n] - tmp[i]).det(tmp[(j + 1) % n] - tmp[j]) < 0) {
            i = (i + 1) % n;
        } else {
            j = (j + 1) % n;
        }
    }
    return res;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    while(~scanf("%d", &n)) {
        for(int i = 0; i < n; i++) {
            scanf("%lf%lf", &ps[i].x, &ps[i].y);
        }

        vector<P> qs = graham();
        double res = 0;
        for(int i = 0; i < qs.size(); i++) {
            for(int j = 0; j < i; j++) {
                res = max(res, dist(qs[i], qs[j]));
            }
        }
        printf("%.0f\n", res);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章