给出连接的城市的高速距离和花费,求起始城市和目的城市之间的最短距离路径,如果有相同距离的最短路径,选择花费最小的路径。
可以使用迪杰斯特拉最短路径求出最短路径,再用深度优先搜索求出最小花费。
我这里直接使用深度优先搜索求出最短路径和最小花费,发现成功提交,没有超时。
(用时:40:31.74)
#include <bits/stdc++.h>
using namespace std;
struct Node {
int dis;
int cost;
int index;
};
vector<int> shorestPath;
int d;
int shorstDistance = INT_MAX;
int minCost = INT_MAX;
void dfs(vector<Node> nodeVec[],int vis[],int cos,int distance,vector<int> path,int index)
{
if(index==d) {
if(shorstDistance > distance) {
shorstDistance = distance;
minCost =cos;
shorestPath = path;
} else if(shorstDistance == distance && minCost > cos) {
minCost =cos;
shorestPath = path;
}
return;
}
vis[index] = 1;
for(int i=0; i<nodeVec[index].size(); i++) {
if(!vis[nodeVec[index][i].index]) {
path.push_back(nodeVec[index][i].index);
dfs(nodeVec,vis,cos + nodeVec[index][i].cost, distance + nodeVec[index][i].dis, path,nodeVec[index][i].index);
path.pop_back();
}
}
vis[index] = 0;
}
int main()
{
int n,m,s;
scanf("%d%d%d%d",&n,&m,&s,&d);
vector<Node> nodeVec[n];
int x,y,c,distance;
for(int i=0; i<m; i++) {
scanf("%d%d%d%d",&x,&y,&distance,&c);
Node n1,n2;
n1.cost = n2.cost = c;
n1.index = y;
n1.dis = n2.dis = distance;
n2.index = x;
nodeVec[x].push_back(n1);
nodeVec[y].push_back(n2);
}
int vis[n]= {0};
vector<int> path;
path.push_back(s);
dfs(nodeVec,vis,0,0,path,s);
for(int i=0; i<shorestPath.size(); i++) {
if(i==0) {
printf("%d",shorestPath[i]);
} else {
printf(" %d",shorestPath[i]);
}
}
printf(" %d %d\n",shorstDistance,minCost);
return 0;
}