Cod sursa(job #2551997)

Utilizator foodinatorfoodinator foodinator Data 20 februarie 2020 14:37:31
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <fstream>
using namespace std;
int n,i,v[100005],st,dr,x,t,m,k,m1;
ifstream in("cautbin.in");
ofstream out("cautbin.out");
int main()
{
    in>>n;
    for (i=1;i<=n;i++)
        in>>v[i];
    in>>m1;
    for (i=1;i<=m1;i++)
    {
        in>>t>>x;
        if (t==0)
        {
            st=1;
            dr=n;
            k=0;
            while (st<=dr)
            {
                m=(st+dr)/2;
                if (v[m]==x)
                {
                    k=1;
                    while (v[m+1]==x) m++;
                    out<<m<<endl;
                    break;
                }
                else if (v[m]<x) st=m+1;
                else dr=m-1;
            }
            if (k==0) out<<-1<<endl;
        }
        else if (t==2)
        {
            st=1;dr=n;
            while (st<=dr)
            {
                m=(st+dr)/2;
                if (v[m]==x)
                {
                    while (v[m-1]==x) m--;
                    out<<m<<endl;k=1;
                    break;
                }
                else if (v[m]<x)
                {
                    int q=v[m];
                    while (v[m+1]==q) m++;
                    if (v[m+1]>x) {out<<m<<endl;break;}
                    else st=m+1;
                }
                else if (v[m]<x) st=m+1;
                else dr=m-1;
            }
        }
        else if (t==1)
        {
            st=1;dr=n;
            while (st<=dr)
            {
                m=(st+dr)/2;
                if (v[m]==x)
                {
                    while (v[m+1]==x) m++;
                    out<<m<<endl;break;
                }
                else if (v[m]>x)
                {
                    int q=v[m];
                    while (v[m-1]==q) m--;
                    if (v[m-1]<x) {out<<m<<endl;break;}
                    else dr=m-1;
                }
                else st=m+1;
            }
        }
    }
}