Cod sursa(job #1758850)

Utilizator fanache99Constantin-Buliga Stefan fanache99 Data 17 septembrie 2016 23:14:37
Problema Gropi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream cin("gropi.in");
ofstream cout("gropi.out");

const int MAXM = 100000;

struct Point {
    int x;
    int y;

    bool operator < (const Point &other) const {
        return y < other.y;
    }
};

Point v[1 + MAXM];
int sum[1 + MAXM];

int BinarySearch(int x, bool first, int m) {
    int left = 1, right = m;
    while (left <= right) {
        int middle = (left + right) / 2;
        if (v[middle].x == x)
            return middle;
        if (v[middle].x < x)
            left = middle + 1;
        else
            right = middle - 1;
    }
    if (first)
        return left;
    return right;
}

int main() {
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
        cin >> v[i].x >> v[i].y;
    sort(v + 1, v + m + 1);
    for (int i = 2; i <= m; i++) {
        sum[i] = sum[i - 1];
        if (v[i - 1].x != v[i].x)
            sum[i]++;
    }
    int tests;
    cin >> tests;
    for (int test = 1; test <= tests; test++) {
        int x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        if (y1 > y2) {
            swap(y1, y2);
            swap(x1, x2);
        }
        int bucket1 = BinarySearch(y1, true, m);
        if (bucket1 > m) {
            int answer = y2 - y1 + 1;
            if (x1 != x2)
                answer++;
            cout << answer << "\n";
            continue;
        }
        if (y1 == y2) {
            int answer = 1;
            if (x1 != x2)
                answer++;
            cout << answer << "\n";
            continue;
        }
        if (v[bucket1].y == y1)
            bucket1++;
        int bucket2 = BinarySearch(y2, false, m);
        if (bucket1 > bucket2) {
            int answer = y2 - y1 + 1;
            if (x1 != x2)
                answer++;
            cout << answer << "\n";
            continue;
        }
        int answer = sum[bucket2] - sum[bucket1] + y2 - y1 + 1;
        if (v[bucket1].x == x1)
            answer++;
        if (v[bucket2].x == x2)
            answer++;
        cout << answer << "\n";
    }
    return 0;
}