Cod sursa(job #2144662)

Utilizator vladstanciuVlad Stanciu vladstanciu Data 26 februarie 2018 21:12:39
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("cautbin.in");
ofstream out("cautbin.out");

int n;
const int N=100001;
int v[N];
void caut0(int x)
{
     int r=0,pas;
     pas=1<<16;
     while(pas!=0)
     {
        if(r+pas<=n && v[r+pas]<=x)
        {
            r+=pas;
        }
        pas/=2;
     }
     if(v[r]!=x)
     {
         out<<-1<<"\n";
     }
     else
     {
         out<<r<<"\n";
     }
}
void caut1(int x)
{
    int r=0,pas;
     pas=1<<16;
     while(pas!=0)
     {
        if(r+pas<=n && v[r+pas]<=x)
        {
            r+=pas;
        }
        pas/=2;
     }
     out<<r<<"\n";

}
void caut2(int x)
{
     int r=0,pas;
     pas=1<<16;
     while(pas!=0)
     {
        if(r+pas<=n && v[r+pas]<x)
        {
            r+=pas;
        }
        pas/=2;
     }
     out<<r+1<<"\n";
}
int main()
{
    int m,i,k,x;
    in>>n;
    for(i=1 ; i<=n ; i++)
    {
         in>>v[i];
    }
    in>>m;
    for(i=1 ; i<=m ; i++)
    {
        in>>k>>x;
        if(k==0)
        {
            caut0(x);
        }
        if(k==1)
        {
            caut1(x);
        }
        if(k==2)
        {
            caut2(x);
        }
    }
    return 0;
}