Cod sursa(job #1584896)

Utilizator preda.andreiPreda Andrei preda.andrei Data 30 ianuarie 2016 16:31:48
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <cstdio>

using namespace std;

int v[100001];

int caut(int val, int n){
    int i = 0, pas = 1 << 16;

    while(pas != 0){
        if(i + pas <= n && v[i+pas] <= val)
            i += pas;
        pas >>= 1;
    }
    if(v[i] == val)
        return i;
    return -1;
}

int caut1(int val, int n){
    int i = 0, pas = 1 << 16;

    while(pas != 0){
        if(i + pas <= n && v[i+pas] <= val)
            i += pas;
        pas >>= 1;
    }
    return i;
}

int caut2(int val, int n){
    int i = 0, pas = 1 << 16;

    while(pas != 0){
        if(i + pas <= n && v[i+pas] < val)
            i += pas;
        pas >>= 1;
    }
    return i + 1;
}

int main()
{
    FILE *fin = fopen("cautbin.in", "r");
    FILE *fout = fopen("cautbin.out", "w");

    int n, r, tip, val;

    fscanf(fin, "%d", &n);
    for(int i=1; i<=n; ++i)
        fscanf(fin, "%d", &v[i]);
    fscanf(fin, "%d", &r);

    for(int i=1; i<=r; ++i){
        fscanf(fin, "%d%d", &tip, &val);
        if(tip == 0)
            val = caut(val, n);
        else if(tip == 1)
            val = caut1(val, n);
        else val = caut2(val, n);
        fprintf(fout, "%d\n", val);
    }

    return 0;
}