Cod sursa(job #1567537)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 13 ianuarie 2016 14:43:31
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <cstdio>
#include <cctype>
#include <cmath>
#include <algorithm>

#define MaxN 100000
#define MaxB 320
#define BUFFSIZE 5000

using namespace std;

int v[MaxN];
int s[MaxB];

static inline char getChar() {
   static char buff[BUFFSIZE];
   static int pos = BUFFSIZE;

   if (pos == BUFFSIZE) {
      fread(buff, 1, BUFFSIZE, stdin);
      pos = 0;
   }
   return buff[pos++];
}

static inline int readInt() {
   unsigned q = 0;
   char c;

   do {
      c = getChar();
   } while (!isdigit(c));

   do {
      q = (q << 1) + (q << 3) + (c - '0');
      c = getChar();
   } while (isdigit(c));
   return q;
}

int main() {
   freopen("cautbin.in", "r", stdin);
   freopen("cautbin.out", "w", stdout);
   int N, Q, queryType, key;
   int numBuckets, BUCKET;
   int poz;

   N = readInt();
   for (int i = 0; i < N; i++) {
      v[i] = readInt();
   }

   BUCKET = (int) sqrt(N - 1) + 1;
   s[0] = -1;
   numBuckets = 1;
   for (int i = BUCKET - 1; i < N; i += BUCKET) {
      s[numBuckets++] = v[i];
   }

   Q = readInt();
   for (int iter = 0; iter < Q; iter++) {
      queryType = readInt(); key = readInt();

      key -= (queryType == 2);

      poz = upper_bound(s, s + numBuckets, key) - s - 1;
      poz *= BUCKET;
      poz = upper_bound(v + poz, v + min(poz + BUCKET, N), key) - v - 1;

      if (!queryType) {
         if (v[poz] == key) {
            printf("%d\n", poz + 1);
         } else {
            puts("-1");
         }
      } else {
         poz += (queryType == 2);
         printf("%d\n", poz + 1);
      }
   }
   fclose(stdin);
   fclose(stdout);
   return 0;
}