Cod sursa(job #1225878)

Utilizator geekyg89Alexandra Alan geekyg89 Data 3 septembrie 2014 21:16:47
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <math.h>
#include <fstream>
using namespace std;

vector <string> splitting_string(std::istringstream line, char delimiter){
	std::vector<std::string> splits;
	std::string string;
	while( std::getline( line , string , delimiter ) )
	{
		std::cout<<  string  <<endl;
		//push split strings into vector.
	    splits.push_back( string );
	}
	return splits;
}
int v[200000];

int BS( int n, int command, int value)
{
	int position;
	if( command <= 1) position = -1;
	else position = n-1;
	int i = 0;
	int j = n - 1;
	int mid;
	while ( i <= j )
	{

			mid = i + (j - i)/2;
			if ( v[mid] < value)
			{
				i = mid + 1;
				if (command == 1) position = mid;
			}
			else if ( v[mid] > value )
			{
				j = mid - 1;
				if (command == 2) position = mid;
			}
			else
			{
				position = mid;
				if (command <= 1)	i = mid + 1;
				else if (command == 2) j = mid - 1;
			}

	}

	return position;

}

int main() {
	freopen("cautbin.out", "w+", stdout);
	freopen("cautbin.in","r", stdin);
	int n;
	int command;
	int value, value1;
	scanf("%d", &n);
	for ( int i = 0; i < n; i++ )
	{
		scanf("%d", &v[i]);
	}
	scanf("%d", &value1);
	int position;
	while (value1 != 0)
	{
		scanf("%d", &command);
		scanf("%d", &value);
		position = BS( n, command, value);
		if (position == -1)
			printf("%d\n", position);
		else
			printf("%d\n", position+1);
		value1--;
	}
    return 0;
}