Cod sursa(job #897021)

Utilizator ocolisanrvocolisan ocolisanrv Data 27 februarie 2013 18:31:14
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
/*#include<stdio.h>
#include<algorithm>
using namespace std;
FILE *in,*out;
int n,i,m,type,poz,v[100100],var;
int main()
{
    in=fopen("cautbin.in","rt");
    out=fopen("cautbin.out","wt");
    fscanf(in,"%d",&n);

    for(i=1;i<=n;i++)
        fscanf(in,"%d",&v[i]);

    fscanf(in,"%d",&m);
    for(i=1;i<=m;i++)
    {
        fscanf(in,"%d",&type);
        fscanf(in,"%d",&var);
        if(type==0)
        {
            poz=upper_bound(v+1,v+n+1,var)-v-1;
            if(poz<=n && poz>=1 && v[poz]==var)
                fprintf(out,"%d\n",poz);
            else
                fprintf(out,"-1\n");
        }
        if(type==1)
        {
            poz=lower_bound(v+1,v+n+1,var+1)-v-1;
            fprintf(out,"%d\n",poz);
        }
        if(type==2)
        {
            poz=upper_bound(v+1,v+n+1,var-1)-v;
            fprintf(out,"%d",poz);
        }
    }
    fclose(in);
    fclose(out);
    return 0;
} */
#include <stdio.h>
#include <algorithm>
using namespace std;

int V[100100];

int main () {
    int N, M, x, y, i, t;

    freopen("cautbin.in", "r", stdin);
    freopen("cautbin.out", "w", stdout);

    scanf("%d", &N);

    for (i = 1; i <= N; ++ i)
        scanf("%d", &V[i]);

    sort(V + 1, V + N + 1);

    scanf("%d", &M);

    for (i = 1; i <= M; ++ i) {
        scanf("%d%d", &t, &y);

        if (t == 0) {
            x = upper_bound(V + 1, V + N + 1, y) - V - 1;
            if (x <= N && x >= 1 && V[x] == y)
                printf("%d\n", x);
            else
                printf("-1\n");
        } else if (t == 1) {
            x = lower_bound(V + 1, V + N + 1, y + 1) - V - 1;
            printf("%d\n", x);
        } else {
            x = upper_bound(V + 1, V + N + 1, y - 1) - V;
            printf("%d\n", x);
        }
    }
}