【分析】
典型的最短路径问题。以边权作为第二标尺,要求所有最短路径中第二标尺和最小的路径。
注意点就是Dijkstra和DFS函数的书写。
Dijkstra里执行n次的总循环不要弄错了。
【代码】
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 510;
const int INF = (1 << 30) - 1;
int G[maxn][maxn], d[maxn], cost[maxn][maxn];
int c1, c2, dis, cst;
int n, m, st, en;
bool vis[maxn];
vector<int> pre[maxn], path, tmpPath;
int minCost = INF;
void Dijkstra(int st) {
fill(d, d + maxn, INF);
fill(vis, vis + maxn, false);
d[st] = 0;
for (int i = 0; i < n; i++)
{
int u = -1, MIN = INF;
for (int j = 0; j < n; j++)
{
if (vis[j] == false && d[j] < MIN) {
MIN = d[j];
u = j;
}
}
if (u == -1) return;
vis[u] = true;
for (int v = 0; v < n; v++)
{
if (vis[v] == false && G[u][v] != INF) {// 记得给G[][]初始化
if (d[v] > d[u] + G[u][v]) {
d[v] = d[u] + G[u][v];
pre[v].clear();
pre[v].push_back(u);
}
else if (d[v] == d[u] + G[u][v]) {
pre[v].push_back(u);
}
}
}
}
}
void DFS(int v, int st) {
if (v == st) {
tmpPath.push_back(v);
//计算最小权值和
int costSum = 0;
for (int i = 0; i < tmpPath.size() - 1; i++)
{
costSum += cost[tmpPath[i]][tmpPath[i + 1]];
}
if (costSum < minCost) {
minCost = costSum;
path = tmpPath;
}
tmpPath.pop_back();
return;
}
tmpPath.push_back(v);
for (int i = 0; i < pre[v].size(); i++)
{
DFS(pre[v][i], st);
}
tmpPath.pop_back();
}
int main() {
fill(G[0], G[0] + maxn * maxn, INF);
fill(cost[0], cost[0] + maxn * maxn, INF);
scanf("%d%d%d%d", &n, &m, &st, &en);
for (int i = 0; i < m; i++)
{
scanf("%d%d%d%d", &c1, &c2, &dis, &cst);
G[c1][c2] = G[c2][c1] = dis;
cost[c1][c2] = cost[c2][c1] = cst;
}
Dijkstra(st);
DFS(en, st);
for (int i = path.size() - 1; i >=0; i--)
{
printf("%d ", path[i]);
}
printf("%d %d\n", d[en], minCost);
return 0;
}