標籤:
Description
就是最短路
Algorithm
Dijkstra
我就用最水的 未加最佳化的做了一下 理論時間複雜度O(V^2)
V為頂點數
後來想想光一開始賦值INF就用了V^2實在不划算
就做了個hasCost的最佳化,空間換時間,不過也沒有快多少
還是要學優先隊列的最佳化啊
Code第一版
import java.util.Arrays;import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); for (;;) { int n = cin.nextInt(); int m = cin.nextInt(); if (n == 0) break; int[][] cost = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(cost[i], Integer.MAX_VALUE / 2); cost[i][i] = 0; } for (int i = 0; i < m; i++) { int a = cin.nextInt() - 1; int b = cin.nextInt() - 1; int c = cin.nextInt(); cost[a][b] = c; cost[b][a] = c; } int[] d = new int[n]; Arrays.fill(d, Integer.MAX_VALUE / 2); boolean[] used = new boolean[n]; d[0] = 0; for (;;) { int v = -1; for (int u = 0; u < n; u++) { if (!used[u] && (v == -1 || d[u] < d[v])) v = u; } if (v == -1) break; used[v] = true; for (int u = 0; u < n; u++) { d[u] = Math.min(d[u], d[v] + cost[v][u]); } } System.out.println(d[n - 1]); } }}
第二版
import java.util.Arrays;import java.util.Scanner;public class Main { public static void main(String[] args) { final int INF = Integer.MAX_VALUE / 2; Scanner cin = new Scanner(System.in); for (;;) { int n = cin.nextInt(); int m = cin.nextInt(); if (n == 0) break; int[][] cost = new int[n][n]; boolean[][] hasCost = new boolean[n][n]; for (int i = 0; i < m; i++) { int a = cin.nextInt() - 1; int b = cin.nextInt() - 1; int c = cin.nextInt(); cost[a][b] = c; cost[b][a] = c; hasCost[a][b] = true; hasCost[b][a] = true; } int[] d = new int[n]; Arrays.fill(d, INF); boolean[] used = new boolean[n]; d[0] = 0; for (;;) { int v = -1; for (int u = 0; u < n; u++) { if (!used[u] && (v == -1 || d[u] < d[v])) v = u; } if (v == -1) break; used[v] = true; for (int u = 0; u < n; u++) { int w = d[v] + cost[v][u]; if (!hasCost[v][u]) w = INF; d[u] = Math.min(d[u], w); } } System.out.println(d[n - 1]); } }}
HDU 2544 最短路