多源汇迪杰算法,就是把模板的从第一点换成每次从start开始到end
奇怪的是正常提交报超内存,居然用一次System.gc()就能过了???
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static final int N = 1010;
static int n, m;
static int cost[], costtime[];
static int g[][], gcost[][];
static boolean st[];
static final int INF = 1 << 30;
public static void init() {
cost = new int[N];
costtime = new int[N];
g = new int[N][N];
gcost = new int[N][N];
st = new boolean[N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
g[i][j] = INF;
}
g[i][i] = 0;
}
}
public static void main(String[] args) throws IOException {
while (true) {
String s[] = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
if (m + n == 0) break;
init();
for (int i = 0; i < m; i++) {
s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int len = Integer.parseInt(s[2]);
int cost = Integer.parseInt(s[3]);
a--;
b--;
if (len < g[a][b]) {
g[a][b] = g[b][a] = len;
gcost[a][b] = gcost[b][a] = cost;
}
}
s = br.readLine().split(" ");
int start = Integer.parseInt(s[0]);
int end = Integer.parseInt(s[1]);
start--;
end--;
dijkstra(start, end);
System.out.println(costtime[end] + " " + cost[end]);
System.gc();
}
}
public static void dijkstra(int start, int end) {
for (int i = 0; i < n; i++) {
cost[i] = gcost[start][i];
costtime[i] = g[start][i];
}
for (int i = 1; i < n; i++) {
int t = -1;
for (int j = 0; j < n; j++) {
if (!st[j] && (t == -1 || costtime[t] > costtime[j]))
t = j;
}
st[t] = true;
for (int j = 0; j < n; j++) {
if (costtime[t] + g[t][j] < costtime[j] && !st[j]) {
costtime[j] = costtime[t] + g[t][j];
cost[j] = cost[t] + gcost[t][j];
} else if (costtime[t] + g[t][j] == costtime[j] && !st[j]) {
if (cost[t] + gcost[t][j] < cost[j])
cost[j] = cost[t] + gcost[t][j];
}
}
}
}
}