Cod sursa(job #2320400)

Utilizator skoda888Alexandru Robert skoda888 Data 14 ianuarie 2019 18:32:09
Problema Infasuratoare convexa Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
///CONVEX HULL

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iomanip>

struct Coords{
    double x;
    double y;
};

std::vector<Coords> Points;

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

inline bool cmp(const Coords& p1, const Coords& p2) {
    return cross_product(Points[0], p1, p2) < 0;
}

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

    //read nummber of points
    int N;
    in >> N;
    //read in a vector of structs all the points
    double x, y;
    in >> x >> y;
    Points.push_back({x, y});
    int bottom_most = 0;
    for(int i = 1; i < N; ++i){
        in >> x >> y;
        Points.push_back({x, y});

        if(x < Points[bottom_most].x || (x == Points[bottom_most].x && y < Points[bottom_most].y)){
            bottom_most = i;
        }
    }

    //move the bottom most element on position 0
    std::swap(Points[0], Points[bottom_most]);


    //sort Points by the polar angles reported to Points[0]
    std::sort(Points.begin() + 1, Points.end(), cmp);

    Coords stack[N + 1];
    stack[1] = Points[0];
    stack[2] = Points[1];
    int head = 2;
    for (int i = 2; i < N; ++i) {
        while (head >= 2 && cross_product(stack[head - 1], stack[head], Points[i]) > 0)
            --head;
        stack[++head] = Points[i];
    }

    out << head << "\n";
    for (int i = head; i >= 1; --i)
        out << std::fixed <<  std::setprecision(9) << stack[i].x << " " << stack[i].y << "\n";
    return 0;

}