Pagini recente » Cod sursa (job #1975220) | Cod sursa (job #1975214) | Cod sursa (job #1975209) | Cod sursa (job #1975236) | Cod sursa (job #1975225)
#include <vector>
#include <stdio.h>
#include <stdlib.h>
/* cea mai mare pozitie pe care se afla un element cu valoarea x
sau -1 daca aceasta valoare nu se gaseste in sir */
int first_question(std::vector<int> &vector, int left, int right, int element) {
int pivot;
while (left <= right) {
pivot = (left + right) / 2;
if (element >= vector[pivot])
left = pivot + 1;
else
right = pivot - 1;
}
pivot = (left + right) / 2;
if (vector[pivot] > element)
pivot--;
if (vector[pivot] == element)
return pivot;
return -1;
}
/* cea mai mare pozitie pe care se afla un element cu valoarea mai mica
sau egala cu x in sir. Se garanteaza ca cel mai mic numar al sirului
este mai mic sau egal decat x */
int second_question(std::vector<int> &vector, int left, int right, int element) {
int pivot;
while (left < right) {
pivot = (left + right) / 2;
if (element >= vector[pivot])
left = pivot + 1;
else
right = pivot;
}
pivot = (left + right) / 2;
if (vector[pivot] > element)
pivot--;
return pivot;
}
/* cea mai mica pozitie pe care se afla un element cu valoarea
mai mare sau egala cu x in sir. Se garanteaza ca cel mai mare
numar din sir este mai mare sau egal decat x */
int third_question(std::vector<int> &vector, int left, int right, int element) {
int pivot;
while (left < right) {
pivot = (left + right) / 2;
if (element <= vector[pivot])
right = pivot;
else
left = pivot + 1;
}
pivot = (left + right) / 2;
if (vector[pivot] < element)
pivot++;
return pivot;
}
int main () {
int N, M, question, element;
freopen("cautbin.in", "r", stdin);
freopen("cautbin.out", "w", stdout);
scanf("%d", &N);
std::vector<int> vector(N);
for (int i = 1; i <= N; ++ i) {
scanf("%d", &vector[i]);
}
scanf("%d", &M);
while (M--){
// Read questions
scanf("%d %d", &question, &element);
// Call functions according to the type of question
switch (question) {
case 0:
printf("%d\n", first_question(vector, 1, N, element));
break;
case 1:
printf("%d\n", second_question(vector, 1, N, element));
break;
case 2:
printf("%d\n", third_question(vector, 1, N, element));
break;
}
}
return 0;
}