Cod sursa(job #1759344)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 18 septembrie 2016 21:42:56
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>

#define nmax 100001

using namespace std;

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

int n, m;
int A[nmax];

int caut1(int x) {
	int left = 1;
	int right = n;

	while (left <= right) {
		int mij = left + (right-left)/2;
		if (A[mij] == x) {
			while (x == A[mij]) mij++;
			mij--;

			return mij;
		} else if (A[mij] < x)
			left = mij+1;
		else
			right = mij-1;
	}

	return -1;
}

int caut2(int x) {
	int left = 1;
	int right = n;
	int poz = 0;

	while (left <= right) {
		int mij = left + (right-left)/2;
		if (A[mij] <= x) {
			left = mij+1;
			poz = mij;
		} else
			right = mij-1;
	}

	return poz;
}

int caut3(int x) {
	int left = 1;
	int right = n;
	int poz = 0;
	
	while (left <= right) {
		int mij = left + (right-left)/2;
		if (A[mij] < x)
			left = mij+1;
		else {
			right = mij-1;
			poz = mij;
		}
	}

	return poz;
}

void read() {
	f>>n;
	for (int i=1;i<=n;i++)
		f>>A[i];

	f>>m;
	for (int i=1;i<=m;i++) {
		int tip, x;
		f>>tip>>x;
		if (tip == 0) {
			g<<caut1(x)<<'\n';
		} else if (tip == 1) {
			g<<caut2(x)<<'\n';
		} else if (tip == 2) {
			g<<caut3(x)<<'\n';
		}
	}
}

int main() {

	read();
	
	f.close();
	g.close();

	return 0;
}