(SPOJ) Carteiro - Solution

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


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

class Main {
    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 numHouses = Integer.parseInt(s[0]);
        int numPackets = Integer.parseInt(s[1]);

        line = br.readLine();
        s = line.split(" ");
        HashMap<Integer, Integer> mapHouses = new HashMap<>();
        for (int i = 0; i < numHouses; i++) {
            mapHouses.put(Integer.parseInt(s[i]), i);
        }
       
        line = br.readLine();
        s = line.split(" ");
        int time = 0;
        int current = 0;
        for (int i = 0; i < numPackets; i++) {
            int nextHouse = mapHouses.get(Integer.parseInt(s[i]));
            time += (Math.abs(nextHouse-current));
            current = nextHouse;
        }

        bw.write(time+"\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) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução