dijkstra求最短路,出现相同最短路时取花费最小的那条。
代码:
#include <cstdio> #include <cmath> #include <algorithm> #include <iostream> using namespace std; int n, m; int map[1010][1010]; bool vi[1010]; int cost[1010][1010]; int dis[1010]; int price[1010]; int s, t; const int INF = 2100000000; void init() { for (int i = 1; i <= n; ++ i) { vi[i] = false; dis[i] = INF; price[i] = INF; for (int j = 1; j <= n; ++ j) { map[i][j] = INF; } } for (int i = 0; i < m; ++ i) { int from, to, d, p; scanf("%d%d%d%d", &from, &to, &d, &p); map[to][from] = map[from][to] = d; cost[to][from] = cost[from][to] = p; } scanf("%d%d", &s, &t); } void dijkstra() { dis[s] = 0; price[s] = 0; for (int k = 0; k < n; ++ k) { int index = -1; int minn = INF; for (int i = 1; i <= n; ++ i) { if (vi[i]==false && dis[i]<minn) { index = i; minn = dis[i]; } } vi[index] = true; for (int j = 1; j <= n; ++ j) { if (dis[j] > dis[index] + map[index][j]) { dis[j] = dis[index] + map[index][j]; price[j] = price[index] + cost[index][j]; } else if (dis[j] == dis[index] + map[index][j]) { price[j] = min(price[j], price[index]+cost[index][j]); } } } } int main() { while (cin >> n >> m, n || m) { init(); dijkstra(); cout << dis[t] << " " << price[t] << endl; } return 0; }