输入样例:
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
思路+代码
经典的求图的最短路径问题,对于此类问题我们可以利用迪杰斯特拉算法来求解。
有几点细节我们需要注意:
1.我们不仅需要记录到达
j
j
j号点的最短路,还需要记录以最短路到达
j
j
j号点的救援队伍数量,所以在更新最短路径时需要多加一个判断。
如下:
int temp = dis[k]+matrix[k][j];
if(temp < dis[j]){
dis[j] = temp;//距离更新
fa[j] = k;//父节点更新
ans_res[j] = res[j] + ans_res[k];//更新到j点的救援人数
ans_l[j] = ans_l[k];//更新到j点的最短路径条数
}
else if(temp == dis[j]){
ans_l[j] += ans_l[k];//最短路条数的增加
if(ans_res[j] < ans_res[k]+res[j]){
ans_res[j] = ans_res[k]+res[j];//更新救援队伍,使得到j点时数量最大
fa[j] = k;
}
}
2.我在初始化图的距离的时候取到了0x7fffffff,对于该题而言,我们不能取这么大,因为会超出
i
n
t
int
int的范围。
3.对于最后的输出我们利用递归,递归结束的条件是父节点为
−
1
-1
−1。
我们所有的容器的初始化如下:
vector<vector<int> >matrix(n,vector<int>(n,INF));//矩阵记录路径长度
fa = vector<int>(n,-1);
vis = vector<int>(n,0);
dis = vector<int>(n,INF);
ans_res = vector<int>(n,0);
ans_l = vector<int>(n,0);
下面给出全部代码(附注释):
#include<bits/stdc++.h>
#define INF 99999999
#define PII pair<int,int>
#define ll long long
using namespace std;
const int N = 510;
int n, m, st, des;
vector<int >res;//救援队伍数量
vector<int >ans_res, ans_l;//答案救援队及救援最短路条数
vector<int >fa, vis, dis;//父节点,标记是否走过,距离。
void pri(int d){
if(fa[d]!=-1){
pri(fa[d]);
}
cout<<d;
if(d!=des)cout<<" ";
}
void solve(){
cin>>n>>m>>st>>des;
vector<vector<int> >matrix(n,vector<int>(n,INF));//矩阵记录路径长度
for(int i = 0;i < n;i++){
int temp;cin>>temp;
res.push_back(temp);
}
int c1, c2, l;
for(int i = 0;i < m;i++){
cin>>c1>>c2>>l;
matrix[c1][c2] = matrix[c2][c1] = l;
}
// 初始化
fa = vector<int>(n,-1);
vis = vector<int>(n,0);
dis = vector<int>(n,INF);
ans_res = vector<int>(n,0);
ans_l = vector<int>(n,0);
ans_res[st] = res[st];
ans_l[st] = 1;
dis[st] = 0;
//迪杰斯特拉
int k = st;
for(int i = 0;i < n;i++){
vis[k] = 1;
for(int j = 0;j < n;j++){
if(vis[j] == 0){
int temp = dis[k]+matrix[k][j];
if(temp < dis[j]){
dis[j] = temp;//距离更新
fa[j] = k;//父节点更新
ans_res[j] = res[j] + ans_res[k];//更新到j点的救援人数
ans_l[j] = ans_l[k];//更新到j点的最短路径条数
}
else if(temp == dis[j]){
ans_l[j] += ans_l[k];//最短路条数的增加
if(ans_res[j] < ans_res[k]+res[j]){
ans_res[j] = ans_res[k]+res[j];//更新救援队伍,使得到j点时数量最大
fa[j] = k;
}
}
// cout<<k<<"->"<<j<<" "<<ans_res[j]<<" "<<ans_l[j]<<" "<<dis[j]<<endl;
}
}
k = st;
for(int j = 0;j < n;j++){
if(vis[j] == 0){
if(k == st||dis[j] < dis[k])
k = j;
}
}
}
// 输出
cout<<ans_l[des]<<" "<<ans_res[des]<<"\n";
pri(des);
}
int main(){
// cin>>t;
// while(t--)
solve();
return 0;
}