Cod sursa(job #2613497)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 9 mai 2020 21:13:30
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <iostream>
#include <fstream>

int n, v[100005];
int m;

std :: ifstream fin ("cautbin.in");
std :: ofstream fout ("cautbin.out");

void cauta_0 (int x) {
    int st = 1;
    int dr = n;

//    bool gasit = false;
    int mijloc;
    while (st <= dr) {
        mijloc = (st + dr)/2;
        if (v[mijloc] == x) {
            if (v[mijloc+1] == x) {
                st = mijloc + 1;
            } else {
                fout << mijloc << "\n";
//                gasit = true;
                return;
                // cea mai mare pozitie
                break;
            }
        } else {
            if (v[mijloc] < x) {
                st = mijloc + 1;
            } else {
                dr = mijloc - 1;
            }
        }
    }
    /*if (!gasit)*/ fout << -1 << "\n";
}

void cauta_1 (int x) {
    int st = 1;
    int dr = n;

//    bool gasit = false;
    int mijloc;
    while (st <= dr) {
        mijloc = (st + dr) /2;
        if (v[mijloc] <= x) {
            if (v[mijloc + 1] == x and mijloc + 1 <= n) {
                st = mijloc + 1;
            } else {
                fout << mijloc << "\n";
//                gasit = true;
                return;
                break;
            }
        } else {
            dr = mijloc - 1;
        }
    }
    /*if (!gasit)*/ fout << -1 << "\n";
}

void cauta_2 (int x) {
    int st = 1;
    int dr = n;

//    bool gasit = false;
    int mijloc;
    while (st <= dr) {
        mijloc = (st + dr)/2;
        if (v[mijloc] >= x)
        {
            if  (v[mijloc -1] >= x and mijloc - 1 > 0) {
                dr = mijloc - 1;
            } else {
                fout << mijloc << "\n";
//                gasit = true;
                return;
                break;
            }
        } else {
            st = mijloc + 1;
        }
    }
    /*if (!gasit)*/ fout << -1 << "\n";
}

int main() {


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

    fin >> m;
    for (int i = 0; i < m; ++i) {
        int a, b;
        fin >> a >> b;
//        std :: cout << a <<" " << b;
        switch (a) {
            case 0:
                cauta_0(b);
                break;
            case 1:
                cauta_1(b);
                break;
            case 2:
                cauta_2(b);
                break;
        }
    }
    return 0;
}