Cod sursa(job #1688380)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 13 aprilie 2016 14:09:11
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

#define NMax 100005
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");

int a[NMax];
int n,m,p,b;

int caut1(int x){
    int st = 1,dr = n;
    int mij = (st + dr)/2;
    while(st <= dr){
        mij = (st + dr) / 2;
        if(a[mij] == x && (mij == n || a[mij + 1] > a[mij]))
            return mij;
        if(a[mij] > x)
            dr = mij - 1;
        if(a[mij] <= x)
            st = mij + 1;
    }
    return -1;
}
int caut2(int x){
    int st = 1,dr = n;
    int mij = (st + dr)/2;
    while(st <= dr){
        mij = (st + dr) / 2;
        if(a[mij] <= x && (mij == n || a[mij + 1] > a[mij]))
            return mij;
        if(a[mij] > x)
            dr = mij - 1;
        if(a[mij] <= x)
            st = mij + 1;
    }
    return -1;
}
int caut3(int x){
    int st = 1,dr = n;
    int mij = (st + dr)/2;
    while(st <= dr){
        mij = (st + dr) / 2;
        if(a[mij] >= x && a[mij - 1] < a[mij])
            return mij;
        if(a[mij] >= x)
            dr = mij - 1;
        if(a[mij] < x)
            st = mij + 1;
    }
    return -1;
}
int main()
{
    f >> n;
    for(int i = 1; i <= n; ++i)
        f >> a[i];
    f >> m;
    for(int i = 1; i <= m; ++i){
        f >> p >> b;
        if(p == 0)
            g << caut1(b) << '\n';
        if(p == 1)
            g << caut2(b) << '\n';
        if(p == 2)
            g << caut3(b) << '\n';
    }
    return 0;
}