Cod sursa(job #1935386)

Utilizator viftode4Iftode Vlad viftode4 Data 22 martie 2017 11:59:08
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n, k, v[100001], i, j, m, x;
int cautbin(int x)
{
    int dr, st, poz=-1, mij;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=(dr+st)/2;
        if(x==v[mij])
        {
            poz=mij;
            st=mij+1;
        }
        else if(v[mij]<x)
        {
            st=mij+1;
        }
        else dr=mij-1;
    }
    return poz;
}
int caut1(int x)
{
    int dr, st, poz=-1, mij;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=(dr+st)/2;
        if(v[mij]<=x)
        {
            poz=mij;
            st=mij+1;
        }
        else dr=mij-1;
    }
    return poz;
}
int caut2(int x)
{
    int dr, st, poz=-1, mij;
    st=1;
    dr=n;
    while(st<=dr)
    {
        mij=(dr+st)/2;
        if(v[mij]>=x)
        {
            poz=mij;
            dr=mij-1;
        }
        else st=mij+1;
    }
    return poz;
}
int main()
{
    fin>>n;
    for(i=1; i<=n; i++)
        fin>>v[i];
    fin>>m;
    for(i=1; i<=m; i++)
    {
        fin>>k>>x;
        if(k==0)
            fout<<cautbin(x)<<endl;
        else if(k==1)
            fout<<caut1(x)<<endl;
        else if(k==2)
            fout<<caut2(x)<<endl;

    }
    return 0;
}