package util.graph;

import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;

public class DynDjikstra {
    public static State FindShortest(Node start, Node target) {
        PriorityQueue<Node> openSet = new PriorityQueue<>();
        Set<Node> closedSet = new HashSet<>();
        openSet.add(start);
        while (!openSet.isEmpty()) {
            Node current = openSet.poll();
            for (Edge edge : current.edges) {
                Node end = edge.target;
                if (closedSet.contains(end)) {
                    continue;
                }
                State newState = edge.travel(current.last);
                //if (end.equals(target)) {
                    //return newState;
                //}
                if (openSet.contains(end)) {
                    if (end.last.compareTo(newState)>0) {
                        end.last = newState;
                    }
                } else {
                    openSet.add(end);
                    end.last = newState;
                }
            }
            closedSet.add(current);
            if (closedSet.contains(target)) {
                return target.last;
            }
        }

        return target.last;
    }
}

package google.codejam.commons;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Utils {

	public static String[] readFromFile(String fileName) throws IOException {
		String[] lines = null;
		FileInputStream fstream = new FileInputStream(fileName);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine = br.readLine();
		lines = new String[Integer.valueOf(strLine)];
		int i = 0;
		while ((strLine = br.readLine()) != null) {
			lines[i++] = strLine;
		}
		in.close();
		return lines;
	}

	public static void writeToFile(String[] lines, String fileName)
			throws IOException {
		FileWriter outFile = new FileWriter(fileName);
		PrintWriter out = new PrintWriter(outFile);
		for (String line : lines) {
			out.println(line);
		}
		out.close();
	}
}
