Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.*;
- import static java.lang.Integer.parseInt;
- /**
- * Created by arpit on 11/12/16.
- */
- class SHPATH {
- static List<Pair> adj[] = new List[10002];
- static Map<String, Integer> cityMap = new HashMap<>();
- static int d[] = new int[10002];
- static boolean vis[] = new boolean[10002];
- public static void main(String[] args) throws IOException {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- int n, s, p, r;
- String s1[], cityName;
- s = parseInt(br.readLine());
- while (s-- > 0) {
- n = parseInt(br.readLine());
- for (int i = 1; i <= n; i++) {
- adj[i] = new ArrayList<>();
- }
- for (int i = 1; i <= n; i++) {
- cityName = br.readLine();
- cityMap.put(cityName, i);
- //p: no. of neighbours
- p = parseInt(br.readLine());
- for (int j = 0; j < p; j++) {
- s1 = br.readLine().split("\\s");
- int v = parseInt(s1[0]);
- int w = parseInt(s1[1]);
- adj[i].add(new Pair(v, w));
- }
- }
- r = parseInt(br.readLine());
- for (int j = 0; j < r; j++) {
- s1 = br.readLine().split("\\s");
- System.out.println(getShortestPath(adj,n, cityMap.get(s1[0]), cityMap.get(s1[1])));
- }
- }
- }
- private static int getShortestPath(List<Pair>[] adj,int n, int source,int destination) {
- PriorityQueue<Pair>pq=new PriorityQueue<>();
- Arrays.fill(d, 1, n + 1, Integer.MAX_VALUE);
- Arrays.fill(vis, 1, n + 1, false);
- pq.add(new Pair(source,0));
- d[source]=0;
- while (!pq.isEmpty()){
- Pair p=pq.poll();
- int u=p.v;
- if (u == destination) {
- break;
- }
- vis[u]=true;
- for (int i = 0; i < adj[u].size(); i++) {
- int v=adj[u].get(i).v;
- int w=adj[u].get(i).w;
- if (!vis[v]){
- d[v]=Integer.min(d[v],d[u]+w);
- pq.add(new Pair(v,d[v]));
- }
- }
- }
- return d[destination];
- }
- static class Pair implements Comparable<Pair>{
- int v,w;
- public Pair(int v, int w) {
- this.v = v;
- this.w = w;
- }
- @Override
- public int compareTo(Pair pair) {
- return ((Integer)this.w).compareTo(pair.w);
- }
- @Override
- public String toString() {
- return "Pair{" +
- "v=" + v +
- ", w=" + w +
- '}';
- }
- }
- }
Add Comment
Please, Sign In to add comment