Pagini recente » Cod sursa (job #311135) | Cod sursa (job #875299) | Cod sursa (job #639639) | Cod sursa (job #546699) | Cod sursa (job #1008817)
#include <fstream>
#include <vector>
#include <ctime>
#include <iostream>
using namespace std;
//CAUTARE BINARA (ARH EDUCATIONALA)
int vec[100001];
int n;
int highXValue(int val);
int XValue(int val);
int smallXValue(int val);
int main()
{
//declararea fisierelor de intrare/iesire
ifstream IN("cautbin.in");
ofstream OUT("cautbin.out");
//vector de functii pentru inlaturarea conditionalelor din for
/*std::vector<int(*) (int val, vector<int>& vec)> functions;
functions.push_back(XValue);
functions.push_back(smallXValue);
functions.push_back(highXValue);*/
//se citeste nr de numere din vector
IN >> n;
//se citesc numere din lista
for (int i = 0 ; i < n; i++)
{
IN >> vec[i];
}
//se citeste numarul de intrebari
int m; IN >> m;
int type, val;
int ret;
//se iau intrebarile in ordine
for (int i = 0; i < m; i++)
{
//se citesc componentele intrebarii
IN >> type; IN >> val;
if (type == 0)
ret = XValue(val);
else if (type == 1)
ret = highXValue(val);
else if (type == 2)
ret = smallXValue(val);
ret++;
OUT << ret << "\n";
}
return 0;
}
int XValue (int val)
{
int low = 0 , high = n - 1, pivot = (low + high) / 2;
while (vec[pivot] != val && low != high)
{
pivot = (low + high) / 2;
if (vec[pivot] > val)
{
high = pivot;
}
else if (vec[pivot] < val)
{
low = pivot;
}
}
if (vec[pivot] == val)
{
while((pivot + 1) <= n - 1 && vec[pivot + 1] == vec[pivot])
pivot++;
return pivot;
}
else return -1;
}
int highXValue(int val)
{
int low = 0, high = n - 1, pivot = (low + high) / 2;
while (vec[pivot] != val && low != high)
{
pivot = (low + high) / 2;
if (vec[pivot] > val)
{
high = pivot;
}
else if (vec[pivot] < val)
{
low = pivot;
}
}
if (vec[pivot] == val)
{
while((pivot + 1) <= n - 1 && vec[pivot + 1] == vec[pivot])
pivot++;
}
else if (vec[pivot] > val)
{
while (vec[pivot] > val)
pivot--;
pivot++;
}
else if (vec[pivot] < val)
{
while (vec[pivot] < val)
pivot++;
pivot--;
}
return pivot;
}
int smallXValue(int val)
{
int low = 0, high = n - 1, pivot = (low + high) / 2;
while (vec[pivot] != val && low != high)
{
pivot = (low + high) / 2;
if (vec[pivot] > val)
{
high = pivot;
}
else if (vec[pivot] < val)
{
low = pivot;
}
}
if (vec[pivot] == val)
{
while((pivot - 1) >= 0 && vec[pivot - 1] == vec[pivot])
pivot--;
}
else if (vec[pivot] > val)
{
while (vec[pivot] > val)
pivot--;
pivot++;
}
else if (vec[pivot] < val)
{
while (vec[pivot] < val)
pivot++;
pivot--;
}
return pivot;
}