Cod sursa(job #1890906)

Utilizator icansmileSmileSmile icansmile Data 23 februarie 2017 16:24:17
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <sstream>

using namespace std;

int n,m;

void answer(int *elements,int question,int number){
    int *it;
    if (question == 0) {
        it = upper_bound(elements,elements + n,number - 1);

        if(*it == number){
            printf("%lu\n",(it - elements + 1));
        }
        else{
            printf("-1\n");
        }
    } else if (question == 1) {
        it = lower_bound(elements,elements + n,number + 1);
        printf("%lu\n",(it - elements));
    } else {
        it = upper_bound(elements,elements + n,number - 1);
        printf("%lu\n",(it - elements + 1));
    }
}

int main() {
    int question;
    int number;
    int *elements;

    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);

    scanf("%d", &n);

    elements = (int*)malloc(n * sizeof(int));
    for(int i = 0; i < n; i++)
        scanf("%d", &elements[i]);

    scanf("%d", &m);

    for(int i = 0; i < m; i++)
    {
        scanf("%d", &question);
        scanf("%d", &number);

        answer(elements,question,number);
    }

    return 0;
}