Cod sursa(job #1800833)

Utilizator mihai.alphamihai craciun mihai.alpha Data 8 noiembrie 2016 10:22:32
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <stdio.h>
#include <ctype.h>
#include <algorithm>
#define BUF 1 << 17
#define MAX 100001
char buf[BUF];
long long pos = BUF;
FILE *fin, *fout;
inline char next()  {
    if(pos == BUF) fread(buf, 1, BUF, fin), pos = 0;
    return buf[pos++];
}

inline void read(int &x)  {
    char ch;
    x = 0;
    ch = next();
    while(!isdigit(ch))
        ch = next();
    while(isdigit(ch))  {
        x = x * 10 + ch - '0';
        ch = next();
    }
    return;
}
#define L 17
int v[MAX];
int n;
inline int caut0(int x)  {
    int pas;
    int r = 0;
    pas = 1 << L;
    while(pas) {
        if(r + pas <= n && v[r + pas] <= x)
            r += pas;
        pas /= 2;
    }
    if(v[r] == x)
        return r;
    return -1;
}

inline int caut1(int x)  {
    int pas;
    int r = 0;
    pas = 1 << L;
    while(pas)  {
        if(r + pas <= n && v[r + pas] <= x)
            r += pas;
        pas /= 2;
    }
        return r;
}

inline int caut2(int x)  {
    int pas;
    int r = 0;
    pas = 1 << L;
    while(pas)  {
        if(r + pas <= n && v[r + pas] < x)
            r += pas;
        pas /= 2;
    }
    return r + 1;
}
int main()  {
    fin = fopen("cautbin.in", "r");
    fout = fopen("cautbin.out", "w");
    int m, i, op, elem;
    read(n);
    for(i = 1; i <= n; i++)  {
        read(v[i]);
    }
    read(m);
    for(i = 0;i < m;i++)  {
        read(op);
        read(elem);
        if(op == 0)  {
            fprintf(fout, "%d\n", caut0(elem));
        }
        else if(op == 1)  {
            fprintf(fout, "%d\n", caut1(elem));
        }
        else if(op == 2)  {
            fprintf(fout, "%d\n", caut2(elem));
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}