Cod sursa(job #1425988)

Utilizator VirgaTudorVirga Tudor VirgaTudor Data 28 aprilie 2015 18:28:48
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include<fstream>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int a[100005],n,m;
void citire()
{
    int i;
    f>>n;
    for(i=0;i<n;i++)
        f>>a[i];
    f>>m;
    sort(a,a+n);
}
 
void op0(int x)
{
    int sol=-2,st=0,dr=n-1,mid;
    mid=(st+dr)/2;
    while(st<=dr)
	{
        if(a[mid]>x)
            dr=mid-1;
        if(a[mid]<x)
            st=mid+1;
        if(a[mid]==x){
            sol=mid;
            st=mid+1;
        }
        mid=(st+dr)/2;
    }
    g<<sol+1<<"\n";
}
 
void op1(int x)
{
    int sol=0,st=0,dr=n-1,mid;
    mid=(st+dr)/2;
    while(st<=dr)
	{
        if(a[mid]>x)
            dr=mid-1;
        if(a[mid]<=x){
            sol=mid;
            st=mid+1;
        }
        mid=(st+dr)/2;
    }
    g<<sol+1<<"\n";
}
 
void op2(int x)
{
    int sol=0,st=0,dr=n-1,mid;
    mid=(st+dr)/2;
    while(st<=dr)
	{
        if(a[mid]<x)
            st=mid+1;
        if(a[mid]>=x){
            sol=mid;
            dr=mid-1;
        }
        mid=(st+dr)/2;
    }
    g<<sol+1<<"\n";
}
 
int main()
{
    int i,op,x;
    citire();
    for(i=0;i<m;i++)
	{
        f>>op>>x;
        if(op==0) op0(x);
        if(op==1) op1(x);
        if(op==2) op2(x);
    }
	return 0;
}