Cod sursa(job #2159563)

Utilizator crisana stanescu cris Data 11 martie 2018 00:32:52
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
#define c 100001
using namespace std;

int task0(int n, int a[], int x) {
	int ls, ld, r = -1;
	ls = 0;
	ld = n-1;
	cout << "wtf";
	while (ls <= ld)  {
		if (x == a[(ls + ld)/2]) {
			r = (ls + ld)/2;
			break;
		}
		if (x < a[(ls + ld)/2]) 
			ld = (ls + ld)/2 -1;
		if (x > a[(ls + ld)/2]) 
			ls = 1 + (ls + ld)/2;
	}
		if (r != -1) {
			while (a[r] == x)
				r++;
			return r;
		}
	return -1;
}

int task1(int n, int a[], int x) {
	int ls, ld, r = -1, m;
	ls = 0;
	ld = n-1;
	while (ls <= ld)  {
		m = (ld + ls)/2;
		//if (((ld - ls) == 1)  && (x >= a[ls]) && (x <= a[ld])) break;
		if (x >= a[m]) 
			ls = m + 1;
		else
			if (x <= a[m]) 
				ld = m -1;
	}
	cout << ls << " " << ld;
	// if (task0(n,a,x) != -1) return ls ;	
	return m ;

}

int task2(int n, int a[], int x) {
	int ls, ld, r = -1, m;
	ls = 0;
	ld = n - 1;
	while (ls <= ld)  {
		
		m = (ls + ld)/2;
		//if (((ld -ls) <= 1) && (x >= a[ls]) && (x <= a[ld])) break;
		if (x <= a[m]) 
			ld = m-1;
		else
			if (x >= a[m]) 
				ls = m +1 ;
	}	
	return m + 1;

}

int main() {

int m, n, a[c], i, ok=0, ls, ld, r, nr, x;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
f >> n;
for (i = 0; i < n; i++) {
	f >> a[i];
}
f >> m;
for (i=0; i < m; i++) {
	f >> nr;
	f >> x;


	if (nr == 0) {
		g << task0(n,a,x) << endl;
		
	}
	if (nr == 1) {
		g << task1(n,a,x) << endl;

	}
	if (nr == 2) {
		g << task2(n,a,x) << endl;
	}
	}
f.close();
g.close();
return 0;
}