Cod sursa(job #1952521)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 4 aprilie 2017 10:46:08
Problema Gropi Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.88 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>

const int kMaxDim = 100005;

int main() {
    std::ifstream inputFile("gropi.in");
    std::ofstream outputFile("gropi.out");

    int dim, pitCount;
    inputFile >> dim >> pitCount;

    std::vector< std::pair<int, int> > pits(pitCount);
    for (auto& pit : pits)
        inputFile >> pit.second >> pit.first;

    std::sort(pits.begin(), pits.end());

    std::vector< int > partialCost(pitCount - 1);
    for (int i = 0; i < pitCount - 1; ++i) {
        if (pits[i].second == pits[i + 1].second)
            partialCost[i] = (i ? partialCost[i - 1] : 0) + pits[i + 1].first - pits[i].first;
        else
            partialCost[i] = (i ? partialCost[i - 1] : 0) + pits[i + 1].first - pits[i].first + 1;
    }

    int queryCount;
    inputFile >> queryCount;

    while (queryCount--) {
        int xi, yi, xf, yf;
        inputFile >> yi >> xi >> yf >> xf;

        if (xi > xf) {
            std::swap(xi, xf);
            std::swap(yi, yf);
        }

        int firstPit = std::lower_bound(pits.begin(), pits.end(), std::make_pair(xi, 1)) - pits.begin();
        int lastPit = std::upper_bound(pits.begin(), pits.end(), std::make_pair(xf, 2)) - pits.begin() - 1;

        if (firstPit > lastPit) {
            int solution = xf - xi + (yf != yi ? 1 : 0);
            outputFile << solution << '\n';
        }
        else {
            int solution = (lastPit ? partialCost[lastPit - 1] : 0) - (firstPit ? partialCost[firstPit - 1] : 0);
            solution += pits[firstPit].first - xi + (pits[firstPit].second == yi ? 1 : 0);
            solution += xf - pits[lastPit].first + 1 + (pits[lastPit].second == yf ? 1 : 0);
            outputFile << solution << '\n';
        }
    }

    inputFile.close();
    outputFile.close();

    return 0;
}

//Trust me, I'm the Doctor!