Cod sursa(job #941441)

Utilizator Ionut228Ionut Calofir Ionut228 Data 18 aprilie 2013 20:27:23
Problema Gropi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.57 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

int c, n, m;
int z, p, nr, poz1, poz2, x12, y12, x1, x2, y1, y2, d;

struct gropi
{
    int x, y;
};
gropi g[100002];

struct puncte
{
    int poz, xz, yz;
};
puncte zona[100002];

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

int cautbin1(int x)
{
    int l = 0, r = z + 1;
    while (r - l > 1)
    {
        int mij = (l + r) / 2;
        if (zona[mij].xz > x)
            r = mij;
        else
            l = mij;
    }
    return l;
}

int cautbin2(int x)
{
    int l = 0, r = z + 1;
    while (r - l > 1)
    {
        int mij = (l + r ) / 2;
        if (zona[mij].yz < x)
            l = mij;
        else
            r = mij;
    }
    return r;
}

int main()
{
    fin >> c >> n;
    for (int i = 1; i <= n; ++i)
        fin >> g[i].x >> g[i].y;

    sort(g + 1, g + n + 1, cmp);

    if (g[1].x == 1 && g[1].y == 1)
        p = 2;
    else
        p = 1;
    z = 0;
    nr = 1;
    for (int i = 1; i <= n; ++i)
    {
        ++z;
        zona[z].poz = p;
        zona[z].xz = nr;
        while (g[i].x != p)
            ++i;
        zona[z].yz = g[i].y - 1;
        nr = g[i].y;
        if (p == 1)
            p = 2;
        else
            p = 1;
    }
    ++z;
    zona[z].poz = p;
    zona[z].xz = nr;
    zona[z].yz = c;

    fin >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x1 >> y1 >> x2 >> y2;

        if (y1 > y2)
        {
            x12 = x1;
            y12 = y1;
            x1 = x2;
            y1 = y2;
            x2 = x12;
            y2 = y12;
        }
        else if (y1 == y2)
        {
            if (x1 > x2)
            {
                x12 = x1;
                x1 = x2;
                x2 = x12;
            }
        }

        poz1 = cautbin1(x1);
        poz2 = cautbin2(y2);
        d = y2 - y1 + 1;
        bool ok = true;
        int j = y1;
        if (x1 != zona[poz1].poz)
        {
            while (ok == true)
            {
                if (j == zona[poz1 + 1].xz || j > z)
                {
                    --d;
                    ok = false;
                }
                else if (g[j].y != 0 && g[j].x == x1)
                    ok =false;
                ++j;
            }
        }
        d += poz2 - poz1;
        if (x2 != zona[poz2].poz)
            ++d;
        fout << d << "\n";
    }

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