思路:
这道题目考察的点很多,首先我们要求起点S到终点D最短路,可以使用Dijkstra算法,即bfs + 贪心,由题目没有给出M的范围,所以我们无法判断图是稠密图还是稀疏图来决定是否使用优先队列来取得更好的时间复杂度,我采用的是优先队列。
其次,我们需要一个 pre[] 数组来记录最短路上结点的上一个结点,来辅助我们打印最短路径。
最后,我们还要使用 dp[i] 数组记录以i为终点最短路的条数,当我们找到了一条更短的路径时,令 dp[j] = dp[i]。如果没有找到了一个与当前最短路长度相同的路径,令 dp[j] += dp[i]。
AC 代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 600,INF = 0x3f3f3f3f;
struct edge {
int to,w;
edge(int a,int b) {
to = a;
w = b;
}
};
struct node {
int id,dis;
node(int a,int b) {
id = a,
dis = b;
}
bool operator < (const node &x) const {
return dis > x.dis;
}
};
int n,m,s,d,a[N],pre[N];
long long dist[N],disnum[N];
int dp[N]; // 最短路条数
bool done[N];
vector<edge> v[N];
void Dijkstra() {
// 初始化距离,救援队数量
for(int i = 0; i < n; i ++)
dist[i] = INF;
dist[s] = 0,disnum[s] = a[s],dp[s] = 1;
pre[s] = -1;
priority_queue<node> q;
q.push(node(s,dist[s]));
while(!q.empty()) {
node u = q.top();
q.pop();
if(done[u.id]) continue;
done[u.id] = true;
for(auto e : v[u.id]) {
if(done[e.to])
continue;
// 找到更小的距离
if(dist[e.to] > e.w + dist[u.id]) {
dist[e.to] = e.w + dist[u.id];
disnum[e.to] = a[e.to] + disnum[u.id];
dp[e.to] = dp[u.id];
pre[e.to] = u.id;
q.push(node(e.to,dist[e.to]));
}
// 在距离相同情况下,找到更多的人数
else if(dist[e.to] == e.w + dist[u.id]) {
dp[e.to] += dp[u.id];
if(disnum[e.to] < a[e.to] + disnum[u.id]) {
disnum[e.to] = a[e.to] + disnum[u.id];
//q.push(node(e.to,dist[e.to]));
pre[e.to] = u.id;
}
}
}
}
}
int main() {
cin>>n>>m>>s>>d;
for(int i = 0; i < n; i ++)
cin>>a[i];
for(int i = 0; i < m; i ++) {
int u,p,w;
cin>>u>>p>>w;
v[u].push_back(edge(p,w));
v[p].push_back(edge(u,w));
}
Dijkstra();
cout<<dp[d]<<" ";
cout<<disnum[d]<<endl;
// 打印路径
stack<int> stk;
int td = d;
while(pre[td] != -1) {
stk.push(pre[td]);
td = pre[td];
}
while(stk.size() > 0) {
cout<<stk.top()<<" ";
stk.pop();
}
cout<<d;
return 0;
}