Cod sursa(job #2654923)

Utilizator PletoPletosu Cosmin-Andrei Pleto Data 2 octombrie 2020 20:22:51
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

int N;
vector <int> V, sum;

int solve(int k, int x) {
    int low = k - 1, high = k + N, mid;
    while (high - low > 1) {
        mid = (low + high) / 2;
        if (sum[mid] < sum[k - 1] + x) {
            low = mid;
        } else {
            high = mid;
        }
    }
    if (high == k + N || V[high] != sum[k - 1] + x) {
        return low - k + 1;
    } else {
        return high - k + 1;
    }
}

int main() {
    int T, s = 0;
    V.push_back(s);
    sum.push_back(s);
    fin >> N >> T;
    for (int x, i = 0; i < N; ++i) {
        fin >> x;
        s += x;
        sum.push_back(s);
        V.push_back(x);
    }
    for (int i = 1; i < N; ++i) {
        s += V[i];
        sum.push_back(s);
        V.push_back(V[i]);
    }
    for (int k, x, i = 0; i < T; ++i) {
        fin >> k >> x;
        fout << solve(k, x) << '\n';
    }
    return 0;
}