Cod sursa(job #1500218)

Utilizator Daniel_UngureanuUngureanu Daniel Daniel_Ungureanu Data 11 octombrie 2015 17:05:04
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int v[100001];
int caut(int li,int ls,int x)
{
    int mij ;
    while(li<=ls)
    {
        mij=(li+ls)/2;
        if(v[mij]==x)
          return mij;
        else
        {
            if(v[mij]<x)
                li=mij+1;
            else
            ls=mij-1;
        }
    }
    return mij;
}
int main()
{
    int n,m,x,p,poz;
    f>>n;
    for(int i=1;i<=n;i++)
        f>>v[i];
    f>>m;
    for(int i=1;i<=m;i++)
    {
        f>>p>>x;
        poz=caut(1,n,x);
        if(p==0)
        {
            if(v[poz]!=x)
                g<<-1<<"\n";
            else
            {
                while(v[poz+1]==x)
                    poz++;
                g<<poz<<"\n";
            }
        }
        if(p==1)
        {
            if(v[poz]==x)
                while(v[poz+1]==x)
                    poz++;
                else
                {
                    poz=caut(1,n,x-1);
                    while(v[poz]>x)
                        poz--;
                    while(v[poz+1]==v[poz])
                        poz++;
                }
            g<<poz<<"\n";
        }
        if(p==2)
        {
            if(v[poz]==x)
                while(v[poz-1]==x)
                    poz--;
            else
            {
                 poz=caut(1,n,x + 1);
                 while(v[poz]<x)
                    poz++;
                 while(v[poz-1]==v[poz])
                    poz--;
            }
            g<<poz<<"\n";
        }
    }
    return 0;
}