题目:
A traveler's map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (≤500) is the number of cities (and hence the cities are numbered from 0 to N−1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:
City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.
Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.
Sample Input:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
Sample Output:
0 2 3 3 40
思路:dfs,1.如果这条路比最短的路要短,更新最短路,费用等于它的费用和路径
2. 如果这条路与最短路相等,更新最少费用和路径
代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main {
static StreamTokenizer sc = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static int ini() throws IOException {
sc.nextToken();
return (int) sc.nval;
}
static int[][] d, f;
static int n, m, start, end;
public static void main(String[] args) throws IOException {
n = ini();
m = ini();
start = ini();
end = ini();
d = new int[n][n];
f = new int[n][n];
while (m-- > 0) {
int x = ini();
int y = ini();
int u = ini();
int v = ini();
d[x][y] = d[y][x] = u;
f[x][y] = f[y][x] = v;
}
vis = new boolean[n];
vis[start] = true;
dfs(start, 0, 0, String.valueOf(start));
System.out.println(ans + " " + mind + " " + minf);
}
static boolean[] vis;
static int mind = Integer.MAX_VALUE, minf = Integer.MAX_VALUE;
static String ans = "";
public static void dfs(int start, int cntd, int cntf, String path) {
//剪枝
if (cntd > mind) return;
if (start == end) {
if (mind > cntd) {
mind = cntd;
minf = cntf;
ans = path;
} else if (mind == cntd) {
if (minf > cntf) {
minf = cntf;
ans = path;
}
}
}
for (int i = 0; i < n; i++) {
if (d[start][i] > 0 && !vis[i]) {
vis[i] = true;
dfs(i, cntd + d[start][i], cntf + f[start][i], path + " " + i);
vis[i] = false;
}
}
}
}