(SPOJ) Soma de Casas - Solution

Link to the problem: http://br.spoj.com/problems/SOMA12/

The solution below used Binary Search to find the possible corresponding house to the current house being analysed. Once there is only one pair of houses which sum has the value that we are looking for, when we find a pair of houses which the sum is equal to the given sum, we find the answer to the problem.


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

class Main {
    public int[] houses;
   
    public int binSearch(int lo, int hi, int value) {
        if (lo > hi) {
            return -1;
        }
       
        int m = (lo+hi)/2;
        if (houses[m] < value) {
            return binSearch(m+1, hi, value);
        }
        else if (houses[m] > value) {
            return binSearch(lo, m-1, value);
        }
        else {
            return value;
        }
    }
   
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        String line = br.readLine();
        int numHouses = Integer.parseInt(line);
        houses = new int[numHouses];
        for (int i = 0; i < numHouses; i++) {
            line = br.readLine();
            houses[i] = Integer.parseInt(line);
        }       
       
        line = br.readLine();
        int sum = Integer.parseInt(line);
        for (int i = 0; i < numHouses; i++) {
            int h1 = houses[i];
            int h2 = binSearch(i+1, numHouses-1, (sum-h1));
            if (h2 != -1) {
                bw.write(h1 + " " + h2 + "\n");
                break;
            }
        }
           
        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