Cod sursa(job #2551999)

Utilizator darianegreanDaria Negrean darianegrean Data 20 februarie 2020 14:39:34
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("cautbin.in");
ofstream out("cautbin.out");
int n,v[100],poz,m,t,x;
int main()
{
    in>>n;
    for(int i=1;i<=n;i++)
        in>>v[i];
    in>>m;
    for(int i=1;i<=m;i++)
    {
        in>>t>>x;
        if(t==0)
        {
            int st,dr,ok=0;
            st=1;
            dr=n;
            while(st<=dr)
            {
                poz=(st+dr)/2;
                if(v[poz]==x)
                {
                    ok=1;
                    while(v[poz+1]==x) poz++;
                    cout<<poz<<endl;
                    break;
                }
                else if(v[poz]<x) st=poz+1;
                else dr=poz-1;
           }
        if(ok==0)cout<<"-1";
        }
        else if(t==1)
        {
            int st,dr,ok=0,poz1;
            st=1;dr=n;
            while(st<=dr)
            {
                poz=(st+dr)/2;
                if(v[poz]==x)
                {
                    ok=1;
                    while(v[poz+1]==x) poz++;
                    cout<<poz<<endl;
                    break;
                }
                else if(v[poz]<x) {st=poz+1; poz1=poz;}
                else dr=poz-1;
            }
            if(ok==0)cout<<poz1<<endl;
        }
        else
        {
            int st,dr,ok=0,poz1;
            st=1;dr=n;
            while(st<=dr)
            {
                poz=(st+dr)/2;
                if(v[poz]==x)
                {
                    ok=1;
                    while(v[poz-1]==x) poz--;
                    cout<<poz<<endl;
                    break;
                }
                else if(v[poz]<x)st=poz+1;
                else {dr=poz-1;poz1=poz;}
            }
            if(ok==0) cout<<poz1;
        }
    }
}