Cod sursa(job #2285056)

Utilizator AnimusFabian Animus Data 17 noiembrie 2018 23:25:21
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>

using namespace std;

int n, v[101], k, a, b;

ifstream in("cautbin.in");
ofstream out("cautbin.out");

int caut(int p, int q, int t){
    if(p == q){
        if(v[p] == t) return p;
        else return -1;
    } else {
        int m = p+(q-p)/2;
        if(v[m] == t) return m;
        else if(t < v[m]) caut(p, m-1, t);
        else caut(m+1, q, t);
    }
}

int main(){
    in >> n;

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

    in >> k;
    for(int i = 1; i <= k; i++){
        in >> a >> b;
        if(a == 0){
            int mx = 0;
            int x = caut(1, n, b);
            while(x != -1){
                if(x > mx) mx = x;
                x = caut(x+1, n, b);
            }
            out << mx << '\n';
        } else if(a == 1){
            int mxx = 0;
            for(int j = 1; j <= b; j++){
                int y = caut(1, n, j);
                while(y != -1){
                    if(y > mxx) mxx = y;
                    y = caut(y+1, n, j);
                }
            }
            out << mxx << '\n';
        } else if(a == 2){
            int mn = n+1, xer = 1;
            int z = caut(1, n, b);
            while(z != -1){
                if(mn > z) mn = z;
                z = caut(1, n-xer, b);
                xer++;
            }
            out << mn << '\n';
        }
    }
}