Cod sursă (job #490255)

Utilizator avatar VisoiuAndrei Andrei Visoiu VisoiuAndrei IP ascuns
Problemă Înfășurătoare convexă Compilator cpp | 1,58 kb
Rundă Arhiva de probleme Status evaluat
Dată 5 oct. 2019 15:56:47 Scor 10
#include <bits/stdc++.h>

using namespace std;

ifstream in("infasuratoare.in");
ofstream out("infasuratoare.out");

const int NMAX = 120000;

struct punct {
    int x, y;
};

int N, nrP;
punct P[NMAX+1], st[NMAX+1];

long long dist2(const punct& A, const punct& B) {
    long long dX = A.x - B.x,
              dY = A.y - B.y;
    return dX * dX + dY * dY;
}

long long det(const punct& A, const punct& B, const punct& C) {
    return 1LL * (A.x - B.x) * (A.y - C.y) - 1LL * (A.y - B.y) * (A.x - C.x);
}

bool compd(const punct& A, const punct& B) {
    long long dd = det(P[1], A, B);
    if(dd == 0)
        return dist2(P[1], A) < dist2(P[1], B);
    return dd < 0;
}


bool compx(const punct& A, const punct& B) {
    if(A.x == B.x) return A.y < B.y;
    return A.x < B.x;
}

void graham() {
    sort(P+2, P+N+1, compd);
    st[1] = P[1];
    st[2] = P[2];

    nrP = 2;

    for(int i = 3; i <= N; i++) {
        long long d = det(st[nrP-1], st[nrP], P[i]);
        if(d == 0) st[nrP] = P[i++];
        else
            if(d < 0)
                st[++nrP] = P[i++];
            else if(nrP >= 2) nrP--;

    }

    if(det(st[nrP-1], st[nrP], P[1]) == 0) nrP--;
}

void show() {
    out << nrP << '\n';
    for(int i = nrP; i >= 1; i--)
        out << st[i].x << ' ' << st[i].y << '\n';
}

int main()
{
    in >> N;
    int pMin = 1;
    for(int i = 1; i <= N; i++) {
        in >> P[i].x >> P[i].y;
        if(compx(P[i], P[pMin]))
            pMin = i;
    }
    swap(P[1], P[pMin]);

    graham();

    show();
    return 0;
}