这个题可以在一个Dijkstra()中完成,但是有维护两个起点,因为是不同的。DFS回溯的时候要记得pop_back();
有什么问题可以在评论区留言,看到会解答的。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 520;
const int INF = 999999999;
int n, G[maxn][maxn], tim[maxn][maxn], dis[maxn], tme[maxn];
int start, dst, minShort = INF, fast = INF;
bool vis1[maxn], vis2[maxn];
vector<vector<int>> path1, path2;
vector<int> ans1, ans2, temppath;
void Dijkstra(int root) {
fill (dis, dis + maxn, INF);
fill (tme, tme + maxn, INF);
dis[root] = 0;
tme[root] = 0;
for (int i = 0; i < n; i++) {
int u1 = -1, MIN1 = INF, u2 = -1, MIN2 = INF;
for (int j = 0; j < n; j++) {
if (vis1[j] == false && MIN1 > dis[j]) {
u1 = j;
MIN1 = dis[j];
}
}
for (int j = 0; j < n; j++) {
if (vis2[j] == false && MIN2 > tme[j]) {
u2 = j;
MIN2 = tme[j];
}
}
if (u1 == -1) return;
vis1[u1] = true;
if (u2 == -1) return;
vis2[u2] = true;
for (int v = 0; v < n; v++) {
if (vis1[v] == false && G[u1][v] != INF) {
if (dis[u1] + G[u1][v] < dis[v]) {
dis[v] = dis[u1] + G[u1][v];
path1[v].clear();
path1[v].push_back(u1);
}
else if (dis[u1] + G[u1][v] == dis[v]) {
path1[v].push_back(u1);
}
}
if (vis2[v] == false && tim[u2][v] != INF) {
if (tme[u2] + tim[u2][v] < tme[v]) {
tme[v] = tme[u2] + tim[u2][v];
path2[v].clear();
path2[v].push_back(u2);
}
else if (tme[u2] + tim[u2][v] == tme[v]) {
path2[v].push_back(u2);
}
}
}
}
}
void DFS1 (int End, int cost) {
temppath.push_back(End);
if (start == End) {
if (cost < fast) {
ans1 = temppath;
fast = cost;
}
temppath.pop_back();
return;
}
for (int i = 0; i < path1[End].size(); i++) {
int next = path1[End][i];
DFS1(next, cost + tim[next][End]);
}
temppath.pop_back();
}
//记得使用前clear。temppath
void DFS2 (int End, int cost) {
temppath.push_back(End);
if (start == End) {
if (cost < minShort) {
ans2 = temppath;
minShort = cost;
}
temppath.pop_back();
return;
}
for (int i = 0; i < path2[End].size(); i++) {
int next = path2[End][i];
DFS2 (next, cost + 1);
}
temppath.pop_back();
}
int main() {
int m;
fill (G[0], G[0] + maxn * maxn, INF);
fill (tim[0], tim[0] + maxn * maxn, INF);
scanf ("%d %d", &n, &m);
path1.resize(n);
path2.resize(n);
for (int i = 0; i < m; i++) {
int v1, v2, oneway, l, t;
scanf ("%d %d %d %d %d", &v1, &v2, &oneway, &l, &t);
if (oneway == 1) {
G[v1][v2] = l;
tim[v1][v2] = tim[v2][v1] = t;
}
else {
G[v1][v2] = G[v2][v1] = l;
tim[v1][v2] = tim[v2][v1] = t;
}
}
scanf ("%d %d", &start, &dst);
Dijkstra(start);
DFS1(dst, 0);
temppath.clear();
DFS2(dst, 0);
int flag = 0;
for (int i = 0; i < ans1.size(); i++) {
if (ans1[i] != ans2[i]) {
flag = 1;
break;
}
}
if (flag != 0) {
printf ("Distance = %d: ", dis[dst]);
for (int i = ans1.size() - 1; i >= 0; i--) {
printf ("%d", ans1[i]);
if(i != 0) printf (" -> ");
}
printf ("\n");
}
else printf ("Distance = %d; ", dis[dst]);
printf ("Time = %d: ", tme[dst]);
for (int i = ans2.size() - 1; i >= 0; i--) {
printf ("%d", ans2[i]);
if(i != 0) printf (" -> ");
}
}