Cod sursa(job #1301633)

Utilizator refugiatBoni Daniel Stefan refugiat Data 26 decembrie 2014 11:32:38
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.49 kb
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<algorithm>
#include<climits>
using namespace std;
struct p
{
    int v,poz;
};
inline bool comp(const p &x,const p &y)
{
    if(x.v<y.v)
        return true;
    else
        if(x.v==y.v)
            if(x.poz<y.poz)
                return true;
    return false;
}
int c0(p v[],int n,int x)
{
    int st,dr,mij;
    st=0;
    dr=n-1;
    int poz=-1;
    while(st<dr)
    {
        mij=st+dr;
        mij=mij/2;
        if(v[mij].v==x)
        {
            poz=v[mij].poz;
            st=mij+1;
        }
        else
            if(v[mij].v>x)
                dr=mij-1;
            else
                st=mij+1;
    }
    if(st==dr)
    {
        if(v[st].v==x)
            poz=v[st].poz;
    }
    return poz;
}

int c1(p v[],int n,int x)
{
    int poz=-1,st=0,dr=n-1,mij;
    while(st<dr)
    {
        mij=st+dr;
        mij=mij/2;
        if(v[mij].v==x)
        {
            poz=mij;
            st=mij+1;
        }
        else
            if(v[mij].v>x)
                dr=mij-1;
            else
            {
                st=mij+1;
                poz=mij;
            }
    }
    if(st==dr)
    {
        if(v[st].v<=x)
            poz=st;
    }
    int m=poz;
    poz=-1;
    for(st=m;st>=0;--st)
        poz=max(poz,v[st].poz);
    return poz;
}

int c2(p v[],int n,int x)
{
    int poz=-1,st=0,dr=n-1,mij;
    while(st<dr)
    {
        mij=st+dr;
        mij=mij/2;
        if(v[mij].v==x)
        {
            poz=mij;
            dr=mij-1;
        }
        else
            if(v[mij].v>x)
            {
                dr=mij-1;
                poz=mij;
            }
            else
                st=mij+1;
    }
    if(st==dr)
    {
        if(v[st].v>=x)
            poz=st;
    }
    int m=poz;
    poz=INT_MAX;
    for(st=m;st<n;++st)
        poz=min(poz,v[st].poz);
    return poz;
}

int main()
{
    ifstream si;
    si.open("cautbin.in");
    FILE* so=fopen("cautbin.out","w");
    int n;
    si>>n;
    int i;
    p v[n];
    for(i=0;i<n;++i)
    {
        si>>v[i].v;
        v[i].poz=i;
    }
    sort(v,v+n,comp);
    int m;
    si>>m;
    int a,b;
    while(m--)
    {
        si>>a>>b;
        if(a==0)
            fprintf(so,"%i\n",c0(v,n,b)+1);
        else
            if(a==1)
                fprintf(so,"%i\n",c1(v,n,b)+1);
            else
                fprintf(so,"%i\n",c2(v,n,b)+1);
    }
}