Cod sursa(job #1498122)

Utilizator DanutCNPR10Penciuc Danut DanutCNPR10 Data 7 octombrie 2015 22:57:34
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int v[100010];
int cautbin(int i,int j,int x)
{
    int mij ;
    while(i <= j)
    {
        mij = (i + j) / 2;
    if(v[mij] == x)
          return mij;
    else
         if(v[mij] < x)
            i = mij + 1;
         else
            j = mij - 1;
    }
    return mij;
}
int main()
{
    int n,m,x,t,c,poz;
    f >> n;
    for(int i = 1; i <= n; i++)
        f >> v[i];
    f >> t;
    for(int i = 1; i <= t; i++)
    {
        f >> c >> x;
        poz = cautbin(1,n,x);
        if( c == 0)
        {
            if(v[poz] != x)
                g << -1 <<'\n';
            else
            {
                poz++;
                while(v[poz] == x)
                    poz++;
                g << poz - 1 <<'\n';
            }
        }
        if( c == 1)
        {
                if(v[poz] == x)
                {
                    poz++;
                    while(v[poz] == x)
                    poz++;
                }
                else
                  {
                    poz = cautbin(1,n,x-1);
                     while(v[poz] > x)
                        poz--;
                     while(v[poz + 1] == v[poz])
                      poz++;
                  }
                    g << poz - 1 <<'\n';

        }
        if( c == 2)
        {
            if(v[poz] == x)
                  while(v[poz - 1] == x)
                    poz--;
            else
            {
                 poz = cautbin(1,n,x + 1);
                 while(v[poz] < x)
                    poz++;
                while(v[poz - 1] == v[poz])
                    poz--;
             }

        g << poz << '\n';
        }
    }
    return 0;
}