Cod sursa(job #1724806)

Utilizator mjmilan11Mujdar Milan mjmilan11 Data 4 iulie 2016 12:13:23
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
using namespace std;

int n, v[100001];

int caut0(int x)
{
    int i = 0, pas = (1 << 16);
    while (pas != 0)
    {
        if (i + pas <= n && v[i + pas] <= x)
            i += pas;
        pas /= 2;
    }
    if (v[i] == x)
        return i;
    return -1;
}

int caut1(int x)
{
    int i = 0, pas = (1 << 16);
    while (pas != 0)
    {
        if (i + pas <= n && v[i + pas] <= x)
            i += pas;
        pas /= 2;
    }
    return i;
}

int caut2(int x)
{
    int i = 0, pas = (1 << 16);
    while (pas != 0)
    {
        if (i + pas <= n && v[i + pas] < x)
            i += pas;
        pas /= 2;
    }
    return 1 + i;
}

int main()
{
    int i, q, w, c;
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f>>n;
    for(i=1; i<=n; i++)
        f>>v[i];
    f>>q;
    for(i=0; i<q; i++)
    {
        f >> w >> c;
        if (w == 0)
            g << caut0(c);
        if (w == 1)
            g << caut1(c);
        if (w == 2)
            g << caut2(c);
        g << "\n";
    }
    return 0;
}