Cod sursa(job #1988337)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 2 iunie 2017 18:55:06
Problema Gropi Scor 100
Compilator cpp Status done
Runda Simulare 13 Marime 1.58 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

const int nmax = 1e5;

pair<int, bool> v[nmax + 1];
int s[nmax + 1];

int main() {
    int nrc, n;
    fin >> nrc >> n;

    for (int i = 1; i <= n; ++ i) {
        int x, y;
        fin >> x >> y;

        v[ i ] = make_pair(y, x - 1);
    }

    sort(v + 1, v + n + 1);
    v[n + 1] = make_pair(nrc + 1, 0);

    s[ 1 ] = 0;
    for (int i = 2; i <= n; ++ i) {
        s[ i ] = s[i - 1] + (v[i - 1].second != v[ i ].second) + v[ i ].first - v[i - 1].first;
    }


    int n2 = 1;
    for (; (n2 << 1) <= n + 1; n2 <<= 1) {
    }

    int m;
    fin >> m;

    while (m --) {
        int a, b, c, d;
        fin >> a >> b >> c >> d;
        -- a; -- c;

        if (b > d) {
            swap(a, c); swap(b, d);
        }

        int x, y;
        x = n + 1;
        y = 0;

        for (int step = n2; step > 0; step >>= 1) { // b e inainte de v[x]
            if (x - step >= 0 && b <= v[x - step].first) {
                x -= step;
            }
        }

        for (int step = n2; step > 0; step >>= 1) { // d e dupa v[y]
            if (y + step <= n && v[y + step].first <= d) {
                y += step;
            }
        }

        int ans;

        if (x <= y) {
            ans = (v[ x ].first - b) + (a == v[ x ].second)
                + s[ y ] - s[ x ]
                + (d - v[ y ].first) + (c == v[ y ].second);
        } else {
            ans = (d - b) + (a != c);
        }

        fout << ans + 1 << "\n";
    }

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