Cod sursa(job #790827)

Utilizator ioana.teocIoana Teoc ioana.teoc Data 22 septembrie 2012 14:29:14
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
//
//  main.cpp
//  CautareBinara
//
//  Created by Ioana Teoc on 9/21/12.
//  Copyright (c) 2012 Ioana Teoc. All rights reserved.
//

#include <iostream>
#include<stdio.h>

using namespace std;
#define maxn 100005

int n, V[maxn];

int search(int x){
    int i = 0, step;
    for(step = 1; step*2 < n; step <<= 1);
    for(i = 0; step; step >>= 1 ){
        if(step + i <= n && V[step + i] <= x)
            i += step;
    }
    return i;
}

int main()
{
    int m, op, x, pos;
    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);
    cin >> n;
    for(int i = 1; i <=n; i++){
        cin >> V[i];
    }
    cin >> m;
    for(int i=1; i<=m; i++){
        cin >> op;
        cin >> x;
        
        pos = search(x);
        if(op == 0){
            if(V[pos] != x){
                cout << -1 << endl;
                continue;
            }
            while(V[pos + 1] == x)
                pos ++;
            cout << pos << endl;
        }
        else if(op == 1){
            if(V[pos] < x){
                cout << pos << endl;
                continue;
            }
            if(V[pos] > x){
                cout << pos - 1 << endl;
                continue;
            }
            while(V[pos + 1] == x)
                pos ++;
            cout << pos << endl;
        }
        else if(op == 2){
            if(V[pos] < x){
                cout << pos + 1 << endl;
                continue;
            }
            if(V[pos] > x){
                cout << pos << endl;
                continue;
            }
            while(V[pos - 1] == x)
                pos--;
            cout << pos << endl;
        }
    }
    
}