Pagini recente » Cod sursa (job #3191863) | Cod sursa (job #294396) | Cod sursa (job #2989218) | Cod sursa (job #355662) | Cod sursa (job #1206920)
#include<stdio.h>
int N, M, *A;
FILE *in, *out;
int binarySearch(int left, int right, int x)
{
int middle = left + ((right - left) / 2);
if (left > right) return middle;
if (A[middle] == x)
return middle;
if (A[middle] < x)
return binarySearch(middle + 1, right, x);
if (A[middle] > x)
return binarySearch(left, middle - 1, x);
}
void read()
{
in = fopen("cautbin.in", "rt");
out = fopen("cautbin.out", "wt");
fscanf(in, "%d", &N);
A = new int[N + 5];
for (int i = 1; i <= N; i++)
{
fscanf(in, "%d", &A[i]);
}
}
void process(){
fscanf(in, "%d", &M);
while (M--)
{
int type, x, foundIndex;
fscanf(in, "%d %d", &type, &x);
foundIndex = binarySearch(1, N, x);
switch (type)
{
case 0:
if (A[foundIndex] != x)
fprintf(out, "-1\n");
else
{
while (A[foundIndex] == x && foundIndex <= N) foundIndex++;
fprintf(out, "%d\n", foundIndex-1);
}
break;
case 1:
if (A[foundIndex] > x)
fprintf(out, "%d\n", foundIndex-1);
else
{
while (A[foundIndex] <= x && foundIndex <= N) foundIndex++;
fprintf(out, "%d\n", foundIndex-1);
}
break;
case 2:
if (A[foundIndex] < x)
fprintf(out, "%d\n", foundIndex + 1);
else
{
while (A[foundIndex] >= x && foundIndex > 0) foundIndex--;
fprintf(out, "%d\n", foundIndex+1);
}
break;
default:
break;
}
}
}
int main()
{
read();
process();
delete[] A;
return 0;
}