Cod sursa(job #2260145)

Utilizator Mgp2005Mgp06Pavel Mihai George Mgp2005Mgp06 Data 14 octombrie 2018 15:10:28
Problema Cautare binara Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>

using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int v[100001];
int main() {
    int n,m,in,sf,c,x,poz,mij;
    f>>n;
    for (int i=1; i<=n; i++) {
        f>>v[i];
    }
    f>>m;
    for (int i=1; i<=m; i++) {
        poz=0;
        f>>c>>x;
        if (c==0) {
            in=1;
            sf=n;
            while (in<=sf &&poz==0) {
                mij=(in+sf)/2;
                if (v[mij]==x) {
                    while (v[mij+1]==x) {
                        mij++;
                    }
                    poz=mij;
                } else {
                    if (v[mij]>x) {
                        sf=mij-1;
                    } else {
                        in=mij+1;
                    }
                }
            }
            if (poz!=0) {
                g<<poz<<'\n';
            } else {
                g<<-1<<'\n';
            }
        }
        if (c==1) {
            in=1;
            sf=n;
            while (in<=sf && poz==0) {
                mij=(in+sf)/2;
                if (v[mij]<=x) {
                    while (v[mij+1]<=x && mij+1<=n) {
                        mij++;
                    }
                    poz=mij;
                } else {


                    if (v[mij]>x) {
                        sf=mij-1;
                    } else {
                        in=mij+1;
                    }
                }
            }
            g<<poz<<'\n';
        }
        if (c==2) {
            in=1;
            sf=n;
            while (in<=sf && poz==0) {
                mij=(in+sf)/2;
                if(v[mij]>=x) {
                        while (v[mij-1]>=x)
                        {
                            mij--;
                        }
                        poz=mij;
                }else
                {
                    if (v[mij]>x) {
                        sf=mij-1;
                    } else {
                        in=mij+1;
                    }
                }
            }
            g<<poz<<'\n';
        }

    }
    return 0;
}