Cod sursa(job #2098155)

Utilizator Luca19Hritcu Luca Luca19 Data 2 ianuarie 2018 14:41:52
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

#include <iostream>
#include <fstream>
using namespace std;
ifstream f("cautbin.in");
ofstream g("cautbin.out");
int n, m, x, i, v[100001], p, a, nmax=-1, nmin=100006;

int caut0(int s, int d)
{
    if(s>d)
        return nmax;
    else
    {
        m=(s+d)/2;
        if(v[m]==x)
        {
            nmax=max(m,nmax);
            caut0(m+1,d);
        }
        else if(x>v[m])
            caut0(m+1,d);
        else
            caut0(s,m-1);
    }
}

int caut1(int s, int d)
{
    if(s>d)
        return nmax;
    else
    {
        m=(s+d)/2;
        if(v[m]<=x)
        {
            nmax=max(m,nmax);
            caut1(m+1,d);
        }
        else
            caut1(s,m-1);
    }
}

int caut2(int s, int d)
{
    if(s>d)
        return nmin;
    else
    {
        m=(s+d)/2;
        if(v[m]>=x)
        {
            nmin=min(m,nmin);
            caut2(s,m-1);
        }
        else
            caut2(m+1,d);
    }
}

int main()
{
    f>>n;
    for(i=1;i<=n;i++)
        f>>v[i];
    f>>p;
    for(i=1;i<=p;i++)
    {
        nmax=-1; nmin=100006;
        f>>a>>x;
        if(a==0)
            g<<caut0(1,n)<<"\n";
        else if(a==1)
            g<<caut1(1,n)<<"\n";

    }
}