Cod sursa(job #834752)

Utilizator cristina.moraruCristina Moraru cristina.moraru Data 15 decembrie 2012 09:54:56
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include<iostream>
#include<stdio.h>

using namespace std;

int bs(unsigned int *v, unsigned x, int start, int stop, int select){
	int mid;
	while(start < stop){
		mid = (start + stop) / 2;
		if(v[mid] == x)
			return mid;
		if(x < v[mid])
			stop = mid;
		if(x > v[mid])
			start = mid+1;
	}
	if(select == 0)
		return -1;
	if(select == 1)
		return stop;
	if(select == 2)
		return start;
}

int main(){

	int N, M, i, select, poz;
	unsigned int *v, x;
	freopen("cautbin.in", "r", stdin);
	freopen("cautbin.out", "w", stdout);
	
	cin >> N;
	v = new unsigned int[N];
	for(i = 0; i < N; i++)
		cin >> v[i];
	cin >> M;
	
	for(i = 0; i < M; i++){
		cin >> select;
		cin >> x;
		if(select == 0){
			poz = bs(v, x, 0, N-1,0);
			while(v[poz+1] == x){
				poz = bs(v, x, poz+1, N-1, 0);
			}
			cout << poz+1 << endl;
		}
		if(select == 1){
			poz = bs(v, x, 0, N-1,1);
			while(v[poz+1] == x){
				poz = bs(v, x, poz+1, N-1, 1);
			}
			cout << poz+1 << endl;
		}
		if(select == 2){
			poz = bs(v, x, 0, N-1, 2);
			while(v[poz-1] == x){
				poz = bs(v, x, 0, poz-1,2);
			}
			cout << poz+1 << endl;
		}
	}
	return 0;
}