You must first select the shortest path. If no Shortest Path is available, that is, several roads are equal, and then take the test. Faster with Dijkstra. Add the corresponding cost when selecting the shortest edge. For details, see the code:
# Include <iostream> # include <cstdio> # include <cstring> using namespace std; # define MAX 1002 # define inf 999999 int map [MAX] [MAX], cost [MAX] [MAX]; int n; void DJ (int st, int en) // Dijkstra inputs the start and end points {int I, j, MIN, v; int flag [MAX], dis [MAX], value [MAX]; for (I = 1; I <= n; I ++) {dis [I] = map [st] [I]; value [I] = cost [st] [I]; // similar to a general template, extra cost} memset (flag, 0, sizeof (flag); flag [st] = 1; for (I = 1; I <= n; I ++) {MIN = inf; for (j = 1; j <= n; j ++) {if (! Flag [j] & MIN> dis [j]) {v = j; MIN = dis [j] ;}} if (MIN = inf) break; flag [v] = 1; for (j = 1; j <= n; j ++) {if (! Flag [j] & map [v] [j] <inf) {if (dis [j]> dis [v] + map [v] [j]) {dis [j] = dis [v] + map [v] [j]; value [j] = value [v] + cost [v] [j]; // select the edge length first, and add the corresponding cost} else if (dis [j] = dis [v] + map [v] [j]). // if the path length is equal, a smaller {if (value [j]> value [v] + cost [v] [j]) is preferentially consumed. value [j] = value [v] + cost [v] [j] ;}}} cout <dis [en] <"" <value [en] <endl; // the shortest path and cost to the end.} int main () {int I, j, m, a, B, d, p, st, en; while (scanf ("% d", & n, & m )! = EOF) {if (n = 0 & m = 0) break; // memset (map, inf, sizeof (map); // memset (cost, inf, sizeof (cost); for (I = 1; I <= n; I ++) for (j = 1; j <= n; j ++) // The Initialization is the maximum value, and the for loop is faster {map [I] [j] = inf; cost [I] [j] = inf;} while (m --) {scanf ("% d", & a, & B, & d, & p ); if (d <map [a] [B] | (d = map [a] [B] & p <cost [a] [B]) {map [a] [B] = map [B] [a] = d; cost [a] [B] = cost [B] [a] = p; // open two-dimensional arrays to record the edge length and cost respectively} scanf ("% d", & st, & en); DJ (st, en );} return 0 ;}