Cod sursa(job #3040122)

Utilizator AleXutzZuDavid Alex Robert AleXutzZu Data 29 martie 2023 12:47:19
Problema Infasuratoare convexa Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#include <cmath>
#include <iomanip>

struct Point {
    Point() = default;

    Point(double x, double y) : x(x), y(y) {}

    double x = 0, y = 0;

    inline friend std::istream &operator>>(std::istream &istream, Point &point) {
        return istream >> point.x >> point.y;
    }

    inline friend std::ostream &operator<<(std::ostream &ostream, const Point &p) {
        return ostream << p.x << " " << p.y;
    }


    static double cross_product(const Point &A, const Point &B, const Point &C) {
        return (B.x - A.x) * (C.y - A.y) - (B.y - A.y) * (C.x - A.x);
    }
};

bool check(std::stack<Point> &stack, const Point &cnd) {
    Point p1 = stack.top();
    stack.pop();
    Point p2 = stack.top();
    stack.push(p1);

    return Point::cross_product(p2, p1, cnd) > 0;
}

int main() {
    std::ifstream input("infasuratoare.in");
    std::ofstream output("infasuratoare.out");

    int n;

    input >> n;
    std::vector<Point> points(n + 1);
    Point ref(INT32_MAX, INT32_MAX);
    int pos = 0;
    for (int i = 1; i <= n; ++i) {
        input >> points[i];

        if (ref.x > points[i].x) ref = points[i], pos = i;
        else if (ref.x == points[i].x) {
            if (ref.y > points[i].y) ref = points[i], pos = i;
        }
    }

    auto itr = points.begin();
    std::advance(itr, pos);
    points.erase(itr);
    n--;

    std::sort(points.begin() + 1, points.end(), [ref](const Point &lhs, const Point &rhs) {
        return Point::cross_product(ref, lhs, rhs) < 0;
    });

    std::stack<Point> stack;
    stack.push(ref);

    for (int i = 1; i <= n; ++i) {
        while (stack.size() >= 2 && check(stack, points[i])) {
            stack.pop();
        }
        stack.push(points[i]);
    }
    output << stack.size() << "\n";
    output << std::setprecision(12) << std::fixed;
    while (!stack.empty()) {
        output << stack.top() << '\n';
        stack.pop();
    }

    return 0;
}