Cod sursa(job #1417982)

Utilizator alexandrustoicaAlexandru Stoica alexandrustoica Data 11 aprilie 2015 17:21:25
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include<iostream>
#include<fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");

int a[101];

int binarytype0(int a[], int low, int high, int x)
{
    int middle;
    if(high==0 || x<a[low]) return -1;
    while(low<high)
    {
        middle=(low+high+1)/2;
        if(x<a[middle]) high=middle-1;
        if(x>=a[middle]) low=middle;
    }
    return low;
}

int binarytype1(int a[], int low, int high, int x)
{
    int middle;
    if(x==a[low]) return low;
    while(low<high)
    {
        middle=(low+high+1)/2;
        if(x<a[middle]) high=middle-1;
        if(x>=a[middle]) low=middle;
    }
    return low;
}

int binarytype2(int a[], int low, int high, int x)
{
    int middle;
    if(x==a[high]) return high;
    while(low<high)
    {
        middle=(low+high)/2;
        if(x<=a[middle]) high=middle;
        if(x>a[middle]) low=middle+1;
    }
    return high;
}

int main()
{
    int n, i, m, type, x;
    f>>n;
    for(i=1; i<=n; i++)
        f>>a[i];
    f>>m;
    while(m!=0)
    {
        f>>type>>x;
        if(type==0) g<<binarytype0(a, 1, n, x)<<'\n';
        if(type==1) g<<binarytype1(a, 1, n, x)<<'\n';
        if(type==2) g<<binarytype2(a, 1, n, x)<<'\n';
        m--;
    }
    return 0;
}