题目
作为一个城市的应急救援队伍的负责人,你有一张特殊的全国地图。在地图上显示有多个分散的城市和一些连接城市的快速道路。每个城市的救援队数量和每一条连接两个城市的快速道路长度都标在地图上。当其他城市有紧急求助电话给你的时候,你的任务是带领你的救援队尽快赶往事发地,同时,一路上召集尽可能多的救援队。
输入格式:
输入第一行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0 ~ (N−1);M是快速道路的条数;S是出发地的城市编号;D是目的地的城市编号。
第二行给出N个正整数,其中第i个数是第i个城市的救援队的数目,数字间以空格分隔。随后的M行中,每行给出一条快速道路的信息,分别是:城市1、城市2、快速道路的长度,中间用空格分开,数字均为整数且不超过500。输入保证救援可行且最优解唯一。
输出格式:
第一行输出最短路径的条数和能够召集的最多的救援队数量。第二行输出从S到D的路径中经过的城市编号。数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
20 30 40 10
0 1 1
1 3 2
0 3 3
0 2 2
2 3 2
输出样例:
2 60
0 1 3
题解+代码
最短路径Dijkstra(set优化版)(记录路径)
+救援队数量help[N],起点到某点救援队总数sumhelp[N],最短路径条数total[N]
while循环中当x==t时不跳出
在松弛操作中增加一步判断:当更新后的距离与未更新的相等时,更新路径数量 (路径p 救援队数量是否更新需根据救援队数量大小判断)
可记录最短路数目total:Dijkstra不是递归,无法计算出路线所有情况,在记录更新total时,只与与终点相连的点的total和路径长度有关,无需关注起点到该点的具体哪条路径
Dijkstra总结:
- 起点到其他所有点的最短距离
- 最短路路径
- 最短路条数
- 路径大小优先时,对点权值判断
#include<bits/stdc++.h>
using namespace std;
const int N = 600;
struct Node {
int y, v;
Node(int _y, int _v) { y = _y, v = _v; }
};
set<pair<int, int>>q;//维护dist数组
vector<Node>edge[N + 1];//节点到节点存在的边及其权值
int n, m, s, d, dist[N + 1];//n个点,m条边,dist其余顶点到起点s的距离
int help[N];//每点救援队数量
int sumhelp[N];//由起点到某点的救援队总数
int total[N];//由起点到某点的最短路径路线总数
//Dijkstra不是递归,无法计算出路线所有情况,在松弛操作取优时已将非最短路径筛除
int p[N];//记录路径
void Dijkstra(int s) {
memset(dist, 127, sizeof(dist));//距离无穷大
memset(p, -1, sizeof(p));
sumhelp[s] = help[s];
dist[s] = 0; q.clear();//距离初始化,清空集合S
//for (auto i : edge[s]) total[i.y] = 1, p[i.y] = s;
total[s] = 1;
for (int i = 0; i < n; i++)
q.insert(make_pair(dist[i], i));//将所有点存入,set自动排序
while (!q.empty()) {
int x = q.begin()->second;//x为未加入C中的dist最小点
q.erase(q.begin());
//printf("x:%d dist%d\n", x,dist[x]);
if (dist[x] > 1 << 30)break;//已找到最短路或没有边
for (auto i : edge[x]) {
if (dist[x] + i.v < dist[i.y]) {
//更新最短距离 路径p 救援队数量 路径数量
q.erase(make_pair(dist[i.y], i.y));
dist[i.y] = min(dist[i.y], dist[x] + i.v);
q.insert(make_pair(dist[i.y], i.y));
p[i.y] = x;
sumhelp[i.y] = sumhelp[x] + help[i.y];
total[i.y] = total[x];
//printf("i.y:%d p[i.y]:%d sumhelp[i.y]:%d total[i.y]:%d\n", i.y,p[i.y], sumhelp[i.y], total[i.y]);
}
else if (dist[x] + i.v == dist[i.y]) {
//更新路径数量 (路径p 救援队数量是否更新需根据救援队数量大小判断)
total[i.y] += total[x];
if (sumhelp[x] + help[i.y] > sumhelp[i.y]) {
sumhelp[i.y] = sumhelp[x] + help[i.y];
p[i.y] = x;
}//printf("p[i.y]:%d sumhelp[i.y]:%d total[i.y]:%d\n", p[i.y], sumhelp[i.y], total[i.y]);
}
}
}
return ;
}
void findpath(int x) {
if (p[x] == -1)return;
findpath(p[x]);
printf("%d ", p[x]);
}
int main() {
scanf("%d%d%d%d", &n, &m, &s, &d);
for (int i = 0; i < n; i++) {
scanf("%d", &help[i]);
}
int x, y, z;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
edge[x].push_back(Node(y, z));
edge[y].push_back(Node(x, z));
}
Dijkstra(s);
printf("%d %d\n", total[d], sumhelp[d]);
findpath(d); printf("%d", d);
return 0;
}
参考代码:https://blog.csdn.net/HNGS04290724/article/details/121211828