Cod sursa(job #1717309)

Utilizator moise_alexandruMoise Alexandru moise_alexandru Data 14 iunie 2016 18:03:18
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
using namespace std;
ifstream in("cautbin.in");
ofstream out("cautbin.out");
const int maxn = 100005;
int v[maxn];
int logn;
int n;
inline int cautbin_0(int x)
{
    int i, pas;
    for (pas = 1; pas < n; pas <<= 1);
    for (i = 0; pas; pas >>= 1)
        if (i + pas <= n && v[i + pas] <= x)
           i += pas;
    return i;
}

inline int cautbin_2(int x)
{
    int st = 1;
    int dr = n;
    int ret = -1;
    while(st <= dr)
    {
        int mij = st + (dr - st) / 2;
        if(x <= v[mij])
        {
            ret = mij;
            dr = mij - 1;
        }
        else
            st = mij + 1;
    }
    return ret;
}

void parsare()
{
    string s = "";
    int poz = 0;
    for(int i = 1; i <= n; i++)
    {
        int nr = 0;
        in >> s;
        int sz = s.size();
        for(int j = 0; j < sz; j++)
            nr = nr * 10 + s[j] - '0';
        v[++poz] = nr;
    }
}

int main()
{
    //freopen("cautbin.in", "r", stdin);
    //freopen("cautbin.out", "w", stdout);
    //scanf("%d", &n);
    in >> n;
    parsare();
    int m;
    //scanf("%d", &m);
    in >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        //scanf("%d%d", &x, &y);
        in >> x >> y;
        if(x == 0 || x == 1)
        {
            int sol = cautbin_0(y);
            if(x == 0 && v[sol] != y)
                //printf("-1");
                out << -1;
            else
                //printf("%d", sol);
                out << sol;
        }
        else
            //printf("%d", cautbin_2(y));
            out << cautbin_2(y);
        //printf("\n");
        out << "\n";
    }
    return 0;
}