Cod sursa(job #1139631)

Utilizator Ionut228Ionut Calofir Ionut228 Data 11 martie 2014 12:51:40
Problema Poligon Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.71 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream fin("poligon.in");
ofstream fout("poligon.out");

int N, M;
int banda, lowerpoints;
int sol, nrdrepte;
double ecm[801], ecn[801];
int D[801];
vector<pair<double, int> > V[801];

struct puncte
{
    int x, y;
};
puncte A[801], B[801], punct;

struct dreapta
{
    int a, b, c;
};
dreapta Ec[801];

bool cmp(puncte a, puncte b)
{
    return (a.x < b.x || (a.x == b.x && a.y < b.y));
}

double gety(int now, double xnow)
{
    return ecm[now] * xnow + ecn[now];
}

int det (puncte pctA, puncte pctB, puncte pctC)
{
    return pctA.x * pctB.y + pctB.x * pctC.y + pctC.x * pctA.y - (pctC.x * pctB.y + pctA.x * pctC.y + pctB.x * pctA.y);
}

int cb1()
{
    int l = 0, r = nrdrepte + 1;

    while (r - l > 1)
    {
        int mid = (l + r) / 2;

        if (D[mid] >= punct.x)
            r = mid;
        else
            l = mid;
    }
    return r;
}

int cb2()
{
    int l = -1, r = V[banda].size();

    while (r - l > 1)
    {
        int mid = (l + r) / 2;

        if (det(A[V[banda][mid].second], A[V[banda][mid].second + 1], punct) <= 0)
            l = mid;
        else
            r = mid;
    }
    return l;
}

int main()
{
    fin >> N >> M;
    for (int i = 1; i <= N; ++i)
    {
        fin >> A[i].x >> A[i].y;
        B[i] = A[i];
    }
    A[N + 1] = A[1];

    sort(B + 1, B + N + 1, cmp);
    B[0].x = B[1].x + 1;
    for (int i = 1; i <= N; ++i)
        if (B[i - 1].x != B[i].x)
            D[++nrdrepte] = B[i].x;

    for (int i = 1; i <= N; ++i)
    {
        Ec[i].a = A[i + 1].y - A[i].y;
        Ec[i].b = A[i].x - A[i + 1].x;
        Ec[i].c = A[i + 1].x * A[i].y - A[i].x * A[i + 1].y;
        ecm[i] = -1.0 * Ec[i].a / Ec[i].b;
        ecn[i] = -1.0 * Ec[i].c / Ec[i].b;
    }

    for (int i = 1; i < nrdrepte; ++i)
    {
        for (int j = 1; j <= N; ++j)
        {
            if (A[j].x == A[j + 1].x) continue;
            if (min(A[j].x, A[j + 1].x) <= D[i] && D[i + 1] <= max(A[j].x, A[j + 1].x))
            {
                double yb = gety(j, (D[i] + D[i + 1]) / 2.0);
                V[i].push_back(make_pair(yb, j));
            }
        }
        sort(V[i].begin(), V[i].end());
    }

    while (M)
    {
        fin >> punct.x >> punct.y;
        if (punct.x < D[1] || punct.x > D[nrdrepte]) continue;

        banda = cb1() - 1;
        lowerpoints = cb2();

        if (lowerpoints && ((lowerpoints & 1) || (!det(A[V[banda][lowerpoints].second], A[V[banda][lowerpoints].second + 1], punct))))
            ++sol;

        --M;
    }

    fout << sol;

    fin.close();
    fout.close();
    return 0;
}