Cod sursa(job #3330091)

Utilizator AndreiEsteNebunAndrei Mateescu AndreiEsteNebun Data 17 decembrie 2025 15:04:40
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

string filename = "cautbin";

ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int NMAX = 100000;
int v[NMAX + 5];

int main()
{
    int n;
    fin>>n;
    for(int i=1;i<=n;i++)
    {
        fin>>v[i];
    }
    int q;
    fin>>q;
    while(q--)
    {
        int type;
        fin>>type;
        if(type==0)
        {
            int x;
            fin>>x;
            int st=1,dr=n;
            int ans = -1;
            while(st<=dr)
            {
                int mij=(st+dr)/2;
                if(v[mij]==x)
                {
                    st = mij + 1;
                    ans = mij;
                }
                else if(v[mij] < x)
                {
                    st = mij + 1;
                }
                else if(v[mij] > x)
                {
                    dr = mij - 1;
                }
            }
            fout<<ans<<'\n';
        }
        if(type==1)
        {
            int x;
            fin>>x;
            int st=1,dr=n;
            int ans = -1;
            while(st<=dr)
            {
                int mij=(st+dr)/2;
                if(v[mij] <= x)
                {
                    ans = mij;
                    st = mij + 1;
                }
                else if(v[mij] > x)
                {
                    dr = mij - 1;
                }
            }
            fout<<ans<<'\n';
        }
        if(type==2)
        {
            int x;
            fin>>x;
            int st=1,dr=n;
            int ans = -1;
            while(st<=dr)
            {
                int mij = (st+dr)/2;
                if(v[mij] >= x)
                {
                    ans = mij;
                    dr = mij - 1;
                }
                else if(v[mij] < x)
                {
                    st = mij + 1;
                }
            }
            fout<<ans<<'\n';
        }
    }
    return 0;
}