Cod sursa(job #3249818)

Utilizator Her0ninjaDragos Rolland Her0ninja Data 17 octombrie 2024 23:02:57
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int n,m,t[100000];
    ifstream f("cautbin.in");
    ofstream g("cautbin.out");
    f>>n;
    for(int i=0;i<n;i++){
        f>>t[i];
    }
    f>>m;
    int a,b;
    for(int l=0;l<m;l++){
        f>>a>>b;
        if (a == 0) {
            int i = 0, j = n - 1, r = -1;
            while (i <= j) {
                int k = (i + j) / 2;
                if (t[k] == b) {
                    r = k;
                    i = k + 1;
                } else if (t[k] < b) {
                    i = k + 1;
                } else {
                    j = k - 1;
                }
            }
            if (r != -1) {
                g << r + 1 << endl;
            } else {
                g << -1 << endl;
            }
        }
        else if(a==1){
            int i=0,j=n-1;
            while(i<=j){
                int k = (i+j) / 2;
                if (t[k] <= b) {
                    i = k+1;
                }
                else j = k-1;
            }
            g<<j+1<<endl;
        }
        else if(a==2){
            int i=0, j=n-1;

            while (i<=j) {
                int k=(i+j) / 2;

                if (t[k] >= b) {
                    j = k - 1;
                }
                else i = k+1;
            }
            g<<i+1<<endl;
        }
    }
    f.close();
    g.close();
    return 0;
}