Pagini recente » Cod sursa (job #1363929) | Cod sursa (job #2531848) | Cod sursa (job #2913359) | Cod sursa (job #222846) | Cod sursa (job #1424876)
#include <stdio.h>
#include <stdlib.h>
unsigned int* Vector;
int N;
int BinarySearch(int Value);
int main()
{
int Index;
int i;
int Order;
unsigned int Value;
int M;
FILE* input;
FILE* output;
output = fopen("cautbin.out","w");
input = fopen("cautbin.in","r");
fscanf(input,"%d",&N);
Vector = (unsigned int*)malloc((N+2)*sizeof(unsigned int));
for(i=1; i<=N; i++) fscanf(input,"%du", Vector+i);
Vector[0]=-1;
Vector[N+1] = 2147483647;
fscanf(input,"%d",&M);
for(i=0; i<M; i++){
fscanf(input,"%d",&Order);
fscanf(input,"%du",&Value);
switch(Order){
case 0:
Index = BinarySearch(Value);
if(Index == -1) {fprintf(output,"%d\n",Index); break;}
while(Vector[Index+1] == Value) Index++;
fprintf(output,"%d\n",Index);
break;
case 1:
Index = BinarySearch(Value);
while(Vector[Index+1] <= Value) Index++;
fprintf(output,"%d\n",Index);
break;
case 2:
Index = BinarySearch(Value);
while(Vector[Index-1] >= Value) Index--;
fprintf(output,"%d\n",Index);
break;
}
}
fclose(output);
fclose(input);
return 0;
}
int BinarySearch(int Value)
{
int Left,Right,Index;
Left = 1;
Right = N;
while(Left <= Right )
{
Index = Left + (Right-Left)/2;
if(Vector[Index] < Value) Left = Index+1;
else if(Vector[Index] > Value) Right = Index-1;
else if(Vector[Index] == Value) return Index;
}
return -1;
}