Cod sursa(job #1901699)

Utilizator DariaPascuPascu Daria DariaPascu Data 4 martie 2017 10:34:32
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

int bin_search0(int x){
l = 1, r = n, ans = -1;
bool found = false;
while(l <= r)
    {
        int m = (l + r) >> 1;
        if(v[m] == x)
            found = true;
        else if(v[m] > x)
        {
            ans = m;
            r = m - 1;
        }
        else
            l = m + 1;
    }
    return (found == true) ? ans : -1;
}

int bin_search1(int x){
l = 1, r = n, ans;
while(l <= r)
    {
        int m = (l + r) >> 1;
        if(v[m] <= x)
            ans = m;
        else if(v[m] > x)
            r = m - 1;
        else
            l = m + 1;
    }
    return ans;
}

int bin_search2(int x){
l = 1, r = n, ans;
while(l <= r)
    {
        int m = (l + r) >> 1;
        if(v[m] >= x)
            ans = m;
        else if(v[m] > x)
            r = m - 1;
        else
            l = m + 1;
    }
    return ans;
}

int main()
{
    ifstream in ("cautbin.in");
    ofstream out ("cautbin.out");

    in >> n;
    for(i = 1; i <= n; ++i)
        in >> v[i];

    in >> bin;
   while (bin--) {
        int type, x;
        in >> type >> x;

        if (type == 0) {
            out << bin_search0(x) << '\n';
        } else if (type == 1) {
            out << bin_search1(x) << '\n';
        } else {
            out << bin_search2(x) << '\n';
        }
    }


    in.close();
    out.close();
    return 0;
}