(SPOJ) Tiro ao Alvo - Solution

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

For every coordinate of a shot, the solution below calculates the distance between the shot and the center of the target. Then, using this information, we can call a Binary Search to find out how many circles cover this shot.


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

class Main {
    public long[] radius;
   
    public int binSearch(int lo, int hi, long value) {
        if (lo > hi) {
            return lo;
        }
       
        int m = (lo+hi)/2;
        if (radius[m] > value) {
            return binSearch(lo, m-1, value);
        }
        if (radius[m] < value) {
            return binSearch(m+1, hi, value);
        }
        else {
            return m;
        }
    }
   
    public static long reader(BufferedReader br) throws NumberFormatException, IOException {     
        long n;
        long resp = 0;     
        int sinal = 1;     
      
        while (true) {         
            n = br.read();         
            if (n >= '0' && n <= '9') {
                break;
            }
            if (n == '-') {
                sinal = -1;
            }         
            if (n == '+') {
                sinal = 1;
            }    
        }
           
        while (true) {         
            resp = resp*10 + n-'0';         
            n = br.read();         
            if (n < '0' || n > '9') {
                break;     
            }
        }
      
        return resp*sinal;     
    }
   
    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();
        String[] s = line.split(" ");
        int numCircles = Integer.parseInt(s[0]);
        int numShots = Integer.parseInt(s[1]);
       
        radius = new long[numCircles];
        for (int i = 0; i < numCircles; i++) {
            long n = reader(br);
            radius[i] = n*n; // avoid to do sqrt to calculate de distance
        }

        long points = 0;
        for (int i = 0; i < numShots; i++) {
            long x = reader(br);
            long y = reader(br);
            long dist = x*x+y*y;
            int radiusIndex = binSearch(0, numCircles-1, dist);
            points += (numCircles-radiusIndex);
        }
       
        bw.write(points+"\n");
       
        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