(SPOJ) Frete da Família Silva - Solution

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

The solution below used Prim because in this problem we need to find the minimum spanning tree.


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

class Main {
    public HashMap<Integer, ArrayList<Edge>> adjList;
  
    public int prim(int numPlaces) {
        Queue<Edge> queue = new PriorityQueue<>();
        queue.add(new Edge(0, 0));
      
        HashSet<Integer> visited = new HashSet<>();
      
        int totalCost = 0;
        while (queue.size() > 0) {
            Edge curr = queue.poll();
            int currPlace = curr.place;
            int currCost = curr.cost;
          
            if (visited.contains(currPlace)) {
                continue;
            }
            visited.add(currPlace);
          
            totalCost += currCost;
            if (visited.size() == numPlaces) {
                return totalCost;
            }
          
            ArrayList<Edge> reachPlaces = adjList.get(currPlace);
            for (int i = 0; i < reachPlaces.size(); i++) {
                queue.add(new Edge(reachPlaces.get(i).place, reachPlaces.get(i).cost));
            }
        }
      
        return totalCost;
    }
  
    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 numPlaces = Integer.parseInt(s[0]);
        int numRoads = Integer.parseInt(s[1]);
      
        adjList = new HashMap<>();
        for (int i = 0; i < numPlaces; i++) {
            adjList.put(i, new ArrayList<Edge>());
        }
      
        for (int j = 0; j < numRoads; j++) {
            line = br.readLine();
            s = line.split(" ");
            int p1 = Integer.parseInt(s[0]);
            int p2 = Integer.parseInt(s[1]);
            int cost = Integer.parseInt(s[2]);
          
            adjList.get(p1).add(new Edge(p2, cost));
            adjList.get(p2).add(new Edge(p1, cost));
        }
      
        bw.write(prim(numPlaces)+"\n");
      
        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 place;
    int cost;
  
    public Edge(int p, int c) {
        place = p;
        cost = c;
    }
  
    public int compareTo(Edge e) {
        return this.cost-e.cost;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução