Skip to content

Instantly share code, notes, and snippets.

@Bekt
Created December 18, 2013 07:24
Show Gist options
  • Save Bekt/8018572 to your computer and use it in GitHub Desktop.
Save Bekt/8018572 to your computer and use it in GitHub Desktop.
Algorithm homework-3 solution.
import java.util.*;
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;
import static java.lang.Integer.*;
import static java.lang.Math.min;
public class Main {
static class Vertex implements Comparable<Vertex> {
int id, distance = MAX_VALUE;
List<Entry<Vertex, Integer>> neighbors = new ArrayList<Entry<Vertex, Integer>>();
public Vertex(int id) {
this.id = id;
}
@Override
public int compareTo(Vertex o) {
return compare(distance, o.distance);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int c = in.nextInt(), r = in.nextInt(), w = in.nextInt();
List<Vertex> vertices = new ArrayList<Vertex>();
for (int i = 0; i < c; i++) {
vertices.add(new Vertex(i + 1));
}
for (int i = 0; i < r; i++) {
int c1 = in.nextInt(), c2 = in.nextInt(), d = in.nextInt();
Vertex vertex1 = vertices.get(c1 - 1);
Vertex vertex2 = vertices.get(c2 - 1);
vertex1.neighbors.add(new SimpleEntry<Vertex, Integer>(vertex2, d));
vertex2.neighbors.add(new SimpleEntry<Vertex, Integer>(vertex1, d));
}
for (int i = 0; i < w; i++) {
vertices.get(in.nextInt() - 1).distance = 0;
}
System.out.println(solve(vertices));
}
static int solve(List<Vertex> vertices) {
int id = -1, min = MAX_VALUE;
for (Vertex v : vertices) {
if (v.distance > 0) {
dijkstra(vertices, v);
Vertex max = Collections.max(vertices);
if (max.distance < min) {
min = max.distance;
id = v.id;
}
v.distance = MAX_VALUE;
}
}
return id;
}
static void dijkstra(List<Vertex> vertices, Vertex source) {
Queue<Vertex> queue = new PriorityQueue<Vertex>();
Set<Vertex> visited = new HashSet<Vertex>();
source.distance = 0;
for (Vertex v : vertices) {
if (v.distance == 0) {
queue.add(v);
} else {
v.distance = MAX_VALUE;
}
}
while (!queue.isEmpty()) {
Vertex u = queue.poll();
visited.add(u);
for (Entry<Vertex, Integer> edge : u.neighbors) {
Vertex v = edge.getKey();
int dist = u.distance + edge.getValue();
if (dist < v.distance) {
v.distance = dist;
if (!visited.contains(v)) {
queue.add(v);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment