Cod sursa(job #2812442)

Utilizator Teodor11Posea Teodor Teodor11 Data 4 decembrie 2021 15:41:37
Problema Cautare binara Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <iostream>
#include <fstream>
using namespace std;

int binary_search_1(int n, int x, int v[100001]) {
    int left = 1, right = n, mid;
    while (left < right) {
        mid = left + (right - left) / 2;
        if (x > v[mid]) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    if (v[left] == x) {
        return left;
    }
    return -1;
}

int binary_search_2(int n, int x, int v[100001]) {
    int left, right, mid;
    do {
        left = 1;
        right = n;
        while (left < right) {
            mid = left + (right - left) / 2;
            if (x > v[mid]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        if (v[left] != x) {
            --x;
        }
    } while (v[left] != x);
    return left;
}

int binary_search_3(int n, int x, int v[100001]) {
    int left, right, mid;
    do {
        left = 1;
        right = n;
        while (left < right) {
            mid = left + (right - left) / 2;
            if (x <= v[mid]) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        if (v[left] != x) {
            ++x;
        }
    } while (v[left] != x);
    return left;
}

int main() {
    ifstream fin("cautbin.in");
    ofstream fout("cautbin.out");
    int n, m, question_type, x, v[100001];
    fin >> n;
    for (int i = 1; i <= n; i++) {
        fin >> v[i];
    }
    fin >> m;
    for (int i = 1; i <= m; i++) {
        fin >> question_type >> x;
        if (question_type == 0) {
            fout << binary_search_1(n, x, v) << '\n';
        } else if (question_type == 1) {
            fout << binary_search_2(n, x, v) << '\n';
        } else {
            fout << binary_search_3(n, x, v) << '\n';
        }
    }
    return 0;
}