求最短路:java
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { private static final int INF = Integer.MAX_VALUE; public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); int[] dist = new int[n + 1]; for (int i = 1; i <= n; ++ i) { dist[i] = INF; } dist[1] = 0; int edgeIndex = 0; int[] lastEdge = new int[n + 1]; int[] end = new int[m + 1]; int[] weight = new int[m + 1]; int[] previous = new int[m + 1]; while (m -- > 0) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); edgeIndex ++; end[edgeIndex] = b; weight[edgeIndex] = c; previous[edgeIndex] = lastEdge[a]; lastEdge[a] = edgeIndex; } Queue<Integer> queue = new LinkedList<>(); boolean[] visited = new boolean[n + 1]; visited[1] = true; queue.add(1); while (! queue.isEmpty()) { Integer top = queue.poll(); visited[top] = false; for (int i = lastEdge[top]; i != 0; i = previous[i]) { if (dist[end[i]] > dist[top] + weight[i]) { dist[end[i]] = dist[top] + weight[i]; if (! visited[end[i]]) { queue.offer(end[i]); visited[end[i]] = true; } } } } System.out.println(dist[n] == INF ? "impossible" : dist[n]); } } }
判斷是否有環:ide
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { private static final int INF = Integer.MAX_VALUE; public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); int[] dist = new int[n + 1]; // 能夠不初始化 int edgeIndex = 0; int[] cnt = new int[n + 1]; int[] lastEdge = new int[n + 1]; int[] end = new int[m + 1]; int[] weight = new int[m + 1]; int[] previous = new int[m + 1]; while (m -- > 0) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); edgeIndex ++; end[edgeIndex] = b; weight[edgeIndex] = c; previous[edgeIndex] = lastEdge[a]; lastEdge[a] = edgeIndex; } Queue<Integer> queue = new LinkedList<>(); boolean[] visited = new boolean[n + 1]; // 全部點出發是否有負環 for (int i = 1; i <= n; ++ i) { visited[i] = true; queue.add(i); } boolean exist = false; while (! queue.isEmpty() && ! exist) { Integer top = queue.poll(); visited[top] = false; for (int i = lastEdge[top]; i != 0; i = previous[i]) { if (dist[end[i]] > dist[top] + weight[i]) { dist[end[i]] = dist[top] + weight[i]; cnt[end[i]] ++; if (cnt[end[i]] >= n) { exist = true; break; } if (! visited[end[i]]) { queue.offer(end[i]); visited[end[i]] = true; } } } } System.out.println(exist); } } }