Cod sursa(job #1147931)

Utilizator c0rn1Goran Cornel c0rn1 Data 20 martie 2014 11:43:58
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <stdio.h>

using namespace std;
int n, a[100010];

int caut0(int st, int dr, int v)
{
    int m;
    while (st<dr)
    {
        m=st+((dr-st)>>1);
        if (a[m]<=v)
            st=m+1;
        else
            dr=m-1;
    }
    m=st+((dr-st)>>1);
    if (a[m]>v && a[m-1]==v)
        return m-1;
    return -1;
}

int caut1(int st, int dr, int v)
{
    int m;
    while (st<dr)
    {
        m=st+((dr-st)>>1);
        if (a[m]<=v)
            st=m+1;
        else
            dr=m;
    }
    m=st+((dr-st)>>1);
    if (a[m]>v)
        m--;
    return m;
}

int caut2(int st, int dr, int v)
{
    int m;
    while (st<dr)
    {
        m=st+((dr-st)>>1);
        if (a[m]<=v)
            dr=m-1;
        else
            st=m;
    }
    m=st+((dr-st)>>1);
    if (a[m]<v)
        m++;
    return m;
}

int main()
{
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);
    scanf("%d", &n);
    for (int i=1; i<=n; i++)
        scanf("%d", &a[i]);
    int T, m, v, q;
    for (scanf("%d", &T); T; T--)
    {
        scanf("%d %d", &m, &v);
        switch (m)
        {
        case 0:
            q=caut0(1, n, v);
            break;
        case 1:
            q=caut1(1, n, v);
            break;
        case 2:
            q=caut2(1, n, v);
            break;
        }
        printf("%d\n", q);
    }
    return 0;
}