Cod sursa(job #1403923)

Utilizator 4ONI2015oni2015 4ONI2015 Data 27 martie 2015 17:32:10
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>

using namespace std;
int n, a[100005], m, t, l, r, mij, i, x, sol;
int main()
{
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);
    scanf("%d", &n);
    for(i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    scanf("%d", &m);
    for(; m; m--)
    {
        scanf("%d%d", &t, &x);
        if(!t)
        {
            sol = 1000000;
            l = 1;
            r = n;
            while(l <= r)
            {
                mij = (l + r) / 2;
                if(a[mij] <= x)
                {
                    if(a[mij] == x)
                        sol = mij;
                    l = mij + 1;
                }
                else
                    r = mij - 1;
            }
            if(sol == 1000000)
                printf("-1\n");
            else
                printf("%d\n", sol);
            continue;
        }
        if(t == 1)
        {
            sol = 1000000;
            l = 1;
            r = n;
            while(l <= r)
            {
                mij = (l + r) / 2;
                if(a[mij] <= x)
                {
                    sol = mij;
                    l = mij + 1;
                }
                else
                    r = mij - 1;
            }
            printf("%d\n", sol);
            continue;
        }
        sol = 1000000;
        l = 1;
        r = n;
        while(l <= r)
        {
            mij = (l + r) / 2;
            if(a[mij] < x)
                l = mij + 1;
            else
            {
                sol = mij;
                r = mij - 1;
            }
        }
        printf("%d\n", sol);
    }
    return 0;
}