Cod sursa(job #2857640)

Utilizator ptudortudor P ptudor Data 25 februarie 2022 23:36:56
Problema Infasuratoare convexa Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.49 kb
#include <bits/stdc++.h>
#define double long double
using namespace std;

#ifdef LOCAL
ifstream in("in.in");
ofstream out("out.out");
#else
ifstream in("infasuratoare.in");
ofstream out("infasuratoare.out");
#endif

struct Point {
    double x,y;

    bool operator < (const Point other) const {
        if (y != other.y) {
            return y < other.y;
        }
        return x < other.x;
    }

    Point operator - (const Point other) const {
        return Point{x - other.x , y - other.y};
    }
};

double angle(Point p) { /// returns in hexadecimal degrees the angle of the Point
    if (p.x == 0) {
        if (p.y == 0) return 0;
        if (p.y > 0) return M_PI/2;
        if (p.y < 0) return M_PI + M_PI / 2;
    }
    if (p.x > 0 && p.y > 0) {
        return atan(p.y / p.x);
    } else if ( p.x > 0 && p.y < 0) {
        return atan(p.y / p.x) + 2 * M_PI; /// pi = 180 degrees
    } else {
        return atan(p.y / p.x) + M_PI;
    }
}
double degree(double radian) {
    return radian * 180 / M_PI;
}

struct Line {
    double a,b,c;
    Line(Point p1, Point p2) {
        if (p1.x == p2.x) {
            b = 0;
            a = 1;
            c = -p1.x;
        }
        double m = ( p1.y - p2.y ) / (p1.x - p2.x);
        double k = p1.y - m * p1.x;
        a = -m;
        b = 1;
        c = -k;
    }
};
double eval(Line l, Point p) {
    return l.a * p.x + l.b * p.y + l.c;
}
bool rightTurn(Point a, Point b, Point c) {
    return angle(b - a) > angle(c - b);
}
vector<Point> pt;
int n;

vector<Point> convexHull() {
    vector<Point> res;

    Point lowLeft = pt[1];
    for (int i = 2; i <= n; i++) {
        if (pt[i] < lowLeft) {
            lowLeft = pt[i];
        }
    }
    sort(pt.begin() + 1, pt.end() , [&](Point a, Point b) {
        ///we move everyone down by this low left guy, then sort this increasing by it's angle.
        ///this is also cool cause this makes the origin(lowLeft the first one)
        return angle(a - lowLeft) < angle(b - lowLeft);
    });

    for (int i = 1; i <= n; i++) {
        while(res.size() >= 2 && rightTurn(res[(int)res.size() - 2] , res[(int)res.size() - 1] , pt[i])) {
            res.pop_back();
        }
        res.push_back(pt[i]);
    }
    return res;
}
int main() {

    in >> n;
    pt.resize(n + 1);
    for (int i = 1; i <= n; i++) {
        double x,y;
        in >> x >> y;
        pt[i] = {x,y};
    }


    auto hull = convexHull();

    out << hull.size() << "\n";
    for (auto k : hull) {
        out << k.x << " " << k.y << "\n";
    }
    out << "\n";
}