(SPOJ) Caminho das pontes - Solution

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

We need to find the path from the canyon to the camp which has the smaller number of holes. Then, we can use Dijkstra's algorithm to solve this problem.


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

class Main {
    public HashMap<Integer, ArrayList<Edge>> adjList;
   
    public int dijkstra(int start, int end) {
        Queue<Edge> queue = new PriorityQueue<Edge>();
        queue.add(new Edge(start, 0));
       
        HashSet<Integer> visited = new HashSet<>();
       
        while (queue.size() > 0) {
            Edge curr = queue.poll();
            int currPillar = curr.pillar;
            int currHoles = curr.hole;
           
            if (visited.contains(currPillar)) {
                continue;
            }
            visited.add(currPillar);
           
            if (currPillar == end) {
                return currHoles;
            }
           
            ArrayList<Edge> reachPillars = adjList.get(currPillar);
            for (int i = 0; i < reachPillars.size(); i++) {
                queue.add(new Edge(reachPillars.get(i).pillar, reachPillars.get(i).hole+currHoles));
            }
        }
       
        return -1;
    }
   
    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 numPillars = Integer.parseInt(s[0]);
        int numBridges = Integer.parseInt(s[1]);
       
        adjList = new HashMap<>();
        for (int i = 0; i < numPillars+2; i++) {
            adjList.put(i, new ArrayList<Edge>());
        }
       
        for (int i = 0; i < numBridges; i++) {
            line = br.readLine();
            s = line.split(" ");
            int p1 = Integer.parseInt(s[0]);
            int p2 = Integer.parseInt(s[1]);
            int hole = Integer.parseInt(s[2]);
           
            adjList.get(p1).add(new Edge(p2, hole));
            adjList.get(p2).add(new Edge(p1, hole));
        }

        bw.write(dijkstra(0, numPillars+1)+"\n");
                   
        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);
    }
}

class Edge implements Comparable<Edge> {
    int pillar;
    int hole;
   
    public Edge(int p, int h) {
        pillar = p;
        hole = h;
    }
   
    public int compareTo(Edge e) {
        return this.hole-e.hole;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução