Cod sursa(job #1657390)

Utilizator FragentisMihai Petru Fragentis Data 20 martie 2016 14:12:36
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <stdio.h>
using namespace std;

int n, m, v[100001], i, x, a;

int cauta(int x)
{
    int s = 1, d = n, m, pos = -1;
    
    while(s<=d)
    {
        m = (s+d)/2;
    
        if(x < v[m])
            d = m-1;
        else if(x > v[m])
            s = m+1;
        else
        {
            pos = m;
            s = m+1;
        }
    }
    
    return pos;
}
int cauta_mic(int x)
{
    int s = 1, d = n, m, pos = -1;
    
    while(s<=d)
    {
        m = (s+d)/2;
    
        if(x < v[m])
            d = m-1;
        else if(x > v[m])
        {
            pos = m;
            s = m+1;
        }
        else
        {
            pos = m;
            s = m+1;
        }
    }
    
    return pos;
}
int cauta_mare(int x)
{
    int s = 1, d = n, m, pos = -1;
    
    while(s<=d)
    {
        m = (s+d)/2;
    
        if(x < v[m])
        {
            pos = m;
            d = m-1;
        }
        else if(x > v[m])
            s = m+1;
        else
        {
            pos = m;
            d = m-1;
        }
    }
    
    return pos;
}

int main()
{
    FILE* fin = fopen("cautbin.in", "r");
    FILE* fout = fopen("cautbin.out", "w");
    fscanf(fin, "%d", &n);
    
    for(i = 1; i<=n; ++i)
        fscanf(fin, "%d", v+i);
        
    fscanf(fin, "%d", &m);
    
    for(i = 1; i<=m; ++i)
    {
        fscanf(fin, "%d%d", &a, &x);
        if(a == 0)
            fprintf(fout, "%d\n", cauta(x));
        else if(a == 1)
            fprintf(fout, "%d\n", cauta_mic(x));
        else
            fprintf(fout, "%d\n", cauta_mare(x));
    }
    
    fclose(fin);
    fclose(fout);
    
    return 0;
}