标签:
就是最短路
Dijkstra
我就用最水的 未加优化的做了一下 理论时间复杂度O(V^2)
V为顶点数
后来想想光一开始赋值INF就用了V^2实在不划算
就做了个hasCost的优化,空间换时间,不过也没有快多少
还是要学优先队列的优化啊
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]);
}
}
}
标签:
原文地址:http://blog.csdn.net/yyecust/article/details/51329382