Cod sursa(job #420056)

Utilizator biroBiro Alexandru biro Data 18 martie 2010 13:25:16
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.82 kb
#include<algorithm>
#define input "back.in"
#define output "back.out"
#define DIM 110
  
using namespace std ;

struct punct()
	{
		int x ;
		int y ;
	}
int n ;
int x ;
int v[DIM] ;
punct t[DIM] ;
  
void read()
    {
        scanf ("%d" , &n ) ;
        for (int i=1 ; i<=n ; ++i)
            {
                scanf ("%d" , &v[i]) ; 
            }
        scanf ("%d" , &x ) ;
		for (int i=1 ; i<=x ; i++)
			{
				scanf ("%d" , &t[i] ) ;
			}
    }
int solve()
    {
        int st=1 ;
        int dr=n ;
        int mijloc ;
		int gasit ;
		int h=0 ;
		while (h<=x)
			{
				gasit=0 ;
				++h ;
				st=1 ;
				dr=n ;
				if(t[h].x==0)
					{
						while (st<=dr)
							{
								mijloc=(st+dr)>>1 ;
								if (v[mijloc]==t[h].y)
									{
										gasit=1 ;
										while (v[mijloc]==t[h].y)
											    {
													mijloc++ ;             
											    }
										printf ("%d\n" , mijloc) ;
									} 
								else
									{
										if (t[h].y>v[mijloc])
											{
												st=mijloc+1 ;
											}
										else
											{
												dr=mijloc-1 ;  
											}
									}
							}
						if (!gasit)
							{
								printf ("-1\n")
							}
					}
				if(t[h].x==1)
					{
						while (st<=dr)
							{
								mijloc=(st+dr)>>1 ;
								if (v[mijloc]==t[h].y)
									{
										gasit=1 ;
										while (v[mijloc]==t[h].y)
											    {
													mijloc-- ;             
											    }
										printf ("%d\n" , mijloc) ;
									} 
								else
									{
										if (t[h].y>v[mijloc])
											{
												st=mijloc+1 ;
											}
										else
											{
												dr=mijloc-1 ;  
											}
									}
							}
						if (!gasit)
							{
								for (int i=1 ; i<=n ; i++)
									{
										if (v[i]>t[h].y)
											{
												printf ("%d\n" , i) ;
												break ;
											}
									}
							}
					}
				if(t[h].x==2)
					{
						while (st<=dr)
							{
								mijloc=(st+dr)>>1 ;
								if (v[mijloc]==t[h].y)
									{
										gasit=1 ;
										while (v[mijloc]==t[h].y)
											    {
													mijloc-- ;             
											    }
										printf ("%d\n" , mijloc) ;
									} 
								else
									{
										if (t[h].y>v[mijloc])
											{
												st=mijloc+1 ;
											}
										else
											{
												dr=mijloc-1 ;  
											}
									}
							}
						if (!gasit)
							{
								for (int i=n ; i>=1 ; i--)
									{
										if (v[i]<t[h].y)
											{
												printf ("%d\n" , i) ;
												break ;
											}
									}
							}
					}
	}
      
int main()
{
    freopen (input,"r",stdin) ;
    freopen (output,"w",stdout) ;
      
    read() ;
    solve() ;
   
}