算法是dijkstra,可以不用DFS,在计算的时候同步更新边的cost和weight,然后将最短路存在vector里面就可以了,相对比较简单
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
int loadw[505][505];
int loadc[505][505];
int loadsumw[505];
int loadsumc[505];
bool vis[505] = {false};
int n,m,s,d;
vector<int>path[505];
void dijkstra(int root)
{
loadsumw[root] = 0;
loadsumc[root] = 0;
for(int i = 0;i<n;i++)
{
int temp = -1;
int minn = INF;
for(int j = 0 ;j<n;j++)
{
if(vis[j]==false&&loadsumw[j]<minn)
{
temp = j;
minn = loadsumw[j];
}
}
if(temp==-1)return ;
vis[temp] = true;
for(int j = 0;j<n;j++)
{
if(vis[j]==false&&loadw[temp][j]<INF)
{
if(loadsumw[j]>loadsumw[temp]+loadw[temp][j])
{
loadsumw[j]=loadsumw[temp]+loadw[temp][j];
loadsumc[j] =loadsumc[temp]+loadc[temp][j];
path[j].clear();
path[j] = path[temp];
path[j].push_back(temp);
}
else if(loadsumw[j]==loadsumw[temp]+loadw[temp][j])
{
if(loadsumc[j] >loadsumc[temp]+loadc[temp][j])
{
loadsumc[j] =loadsumc[temp]+loadc[temp][j];
path[j].clear();
path[j] = path[temp];
path[j].push_back(temp);
}
}
}
}
// for(int j = 0;j<n;j++)
// printf("%d ",loadsumw[j]);
// cout<<endl;
// for(int j = 0;j<n;j++)
// printf("%d ",loadsumc[j]);
// cout<<endl;
}
}
int main()
{
scanf("%d%d%d%d",&n,&m,&s,&d);
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
loadw[i][j] = INF;
for(int i = 0;i<m;i++)
{
int temp1,temp2;
scanf("%d %d",&temp1,&temp2);
scanf("%d %d",&loadw[temp1][temp2],&loadc[temp1][temp2]);
loadw[temp2][temp1] = loadw[temp1][temp2];
loadc[temp2][temp1] = loadc[temp1][temp2];
}
for(int i = 0;i<n;i++)
{
loadsumw[i] = INF;
loadsumc[i] = INF;
}
dijkstra(s);
for(int i = 0;i<path[d].size();i++)
printf("%d ",path[d][i]);
printf("%d %d %d\n",d,loadsumw[d],loadsumc[d]);
return 0;
}