(UVA) Where is the Marble? - Solution 1

I used Binary Search to solve this problem.

import java.io.*;
import java.util.*;

class Main  {
    public static int binarySearch(int[] marbles, int numMarbles, int query) {
        int index = -1;
       
        int lo = 0;
        int hi = numMarbles-1;
        while (lo <= hi) {
            int mi = (lo+hi)/2;
            if (marbles[mi] < query) {
                lo = mi+1;
            }
            else if (marbles[mi] > query) {
                hi = mi-1;
            }
            else {
                hi = mi-1;
                index = mi;
            }
        }
       
        return index;
    }
   
    static int reader(BufferedReader br) throws NumberFormatException, IOException {     
        int n;
        int resp = 0;      
      
        while (true) {         
            n = br.read();         
            if (n >= '0' && n <= '9') {
                break;
            } 
        }
           
        while (true) {         
            resp = resp*10 + n-'0';         
            n = br.read();         
            if (n < '0' || n > '9') {
                break;     
            }
        }
      
        return resp;     
    }
   
    public static void process() throws NumberFormatException, IOException {   
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        int numMarbles = reader(br);
        int numQueries = reader(br);
        int numCase = 0;
        while (numMarbles != 0 || numQueries != 0) {
            int[] marbles = new int[numMarbles];
            for (int i = 0; i < numMarbles; i++) {
                marbles[i] = reader(br);
            }
           
            Arrays.sort(marbles);
       
            bw.write("CASE# " + ++numCase +":\n");
            for (int i = 0; i < numQueries; i++) {
                int query = reader(br);
                int index = binarySearch(marbles, numMarbles, query);
               
                if (index != -1) {
                    bw.write(query + " found at " + (index+1) + "\n");
                }
                else {
                    bw.write(query + " not found\n");
                }
            }
           
            numMarbles = reader(br);
            numQueries = reader(br);
        }       
       
        bw.flush();
        bw.close();
               
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();

        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução