L2-001. 紧急救援
时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
作为一个城市的应急救援队伍的负责人,你有一张特殊的全国地图。在地图上显示有多个分散的城市和一些连接城市的快速道路。每个城市的救援队数量和每一条连接两个城市的快速道路长度都标在地图上。当其他城市有紧急求助电话给你的时候,你的任务是带领你的救援队尽快赶往事发地,同时,一路上召集尽可能多的救援队。
输入格式:
输入第一行给出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
提交代码
一直卡在存在两个最短路径相等时,路径条数相加那里,值得一说的是cmp种的比较符,因为存在这样一种可能即对于某个节点已达到了最短路径,而此时加入了两个进入优先队列,此时最短路径相同,应该比较的是到达该节点的最短路径条数。
#include <iostream>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <cmath>
#include <stack>
#include <string>
#include <queue>
#include <algorithm>
#include <cstdio>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
struct edge {
int x, y, value;
};
struct cmp {
int x;
int dis;
int num;
friend bool operator < (const cmp &a, const cmp &b){
if (a.dis != b.dis) {
return a.dis > b.dis;
}
else {
return a.num < b.num;
}
}
};
int n, m, s, d;
int dis[505], dpnum[505], dpdis[505], num[505], pre[505];
bool visit[505];
vector<edge> G[505];
void addedge(int x, int y, int value) {
G[x].push_back(edge{x,y,value});
G[y].push_back(edge{ y,x,value });
}
void dijistra() {
priority_queue<cmp> q;
for (int i = 0; i < n; ++i) {
dis[i] = INF;
}
dis[s] = 0;
dpnum[s] = num[s];
dpdis[s] = 1;
q.push(cmp{s,dis[s],num[s]});
while (!q.empty()) {
cmp t0 = q.top();
q.pop();
if (visit[t0.x]) {//s到t.x的最短路径已经得到
continue;
}
visit[t0.x] = true;
int si = G[t0.x].size();
for (int i = 0; i < si; ++i) {
edge &t = G[t0.x][i];
if (!visit[t.y]) {
if (dis[t.x] + t.value < dis[t.y]) {
dis[t.y] = dis[t.x] + t.value;
dpnum[t.y] = dpnum[t.x] + num[t.y];
dpdis[t.y] = dpdis[t.x];
pre[t.y] = t.x;
}
else if (dis[t.x] + t.value == dis[t.y]) {
if (dpnum[t.y] < dpnum[t.x] + num[t.y]) {
dpnum[t.y] = dpnum[t.x] + num[t.y];
pre[t.y] = t.x;
}
dpdis[t.y] += dpdis[t.x];
}
q.push(cmp{t.y,dis[t.y],dpdis[t.y]});
}
}
}
}
int main() {
scanf("%d%d%d%d", &n, &m, &s, &d);
for (int i = 0; i < n; ++i) {
scanf("%d", &num[i]);
}
int x, y, z;
for (int i = 0; i < m; ++i) {
scanf("%d%d%d", &x,&y,&z);
addedge(x, y, z);
}
dijistra();
stack<int> sta;
int k = d;
sta.push(d);
while (k != s) {
k = pre[k];
sta.push(k);
}
printf("%d %d\n", dpdis[d], dpnum[d]);
printf("%d", sta.top());
sta.pop();
while (!sta.empty()) {
printf(" %d", sta.top());
sta.pop();
}
putchar('\n');
return 0;
}