(SPOJ) Número Proibido - Solution

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

The solution below keeps the forbidden numbers in a structure (HashSet). Then, for every query, we only need to check if the structure contains the numbers. As we are using a HashSet, this operation costs only O(1).


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

class Main {
    public static long reader(BufferedReader br) throws NumberFormatException, IOException {     
        long n;
        long 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 void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        long numForbiddenNumbers = reader(br);
       
        HashSet<Long> numbers = new HashSet<>();
        for (int i = 0; i < numForbiddenNumbers; i++) {
            numbers.add(reader(br));
        }
       
        String line = br.readLine();
        while (line != null) {
            if (numbers.contains(Long.parseLong(line))) {
                bw.write("sim\n");
            }
            else {
                bw.write("nao\n");
            }
           
            line = br.readLine();
        }
       
        br.close();
        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