1030 Travel Plan (30 分)
A traveler‘s map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (≤500) is the number of cities (and hence the cities are numbered from 0 to N?1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:
City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.
Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.
Sample Input:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
Sample Output:
0 2 3 3 40
思路: 1、这道题仅仅使用dfs就可以解决,当然使用迪杰斯特拉更好,可惜我现在还不会 2、一定要小心这是一个无向图(第二次犯错误了),使用vector构造邻接表会快一点。 3、存路径的时候使用vector动态数组会简单一点,因为不需要维持索引
#include<iostream> #include<vector> #include<algorithm> #include<queue> using namespace std; struct Node { int to; int dis; int cost; }; vector<vector<Node> >node; int visited[500]; int minCost=10000; int minDis=10000; //int path[501]; //int tPath[501]; //int i=0; //int pathNum=0; vector<int>path; vector<int>tPath; void dfs(int start,int endC,int cost,int dis,int n) { if(start==endC) { //output(n); if(dis<minDis) { minDis=dis; minCost=cost; path=tPath; //copy(tPath,tPath+i,path); //pathNum=i; //return; } else if(dis==minDis&&cost<minCost) { //minDis=min(dis,minDis); minCost=cost; path=tPath; } return; } for(auto temp:node[start]) { if(visited[temp.to]!=1) { tPath.push_back(temp.to); visited[temp.to]=1; dfs(temp.to,endC,temp.cost+cost,temp.dis+dis,n); visited[temp.to]=0; tPath.pop_back(); } } //i--; } int main() { int n,m,start,endC; cin>>n>>m>>start>>endC; node.resize(n); for(int i=0; i<m; i++) { Node temp; int start; scanf("%d%d%d%d",&start,&temp.to,&temp.dis,&temp.cost); node[start].push_back(temp); //这是一个无向图 int endC=temp.to; temp.to=start; node[endC].push_back(temp); } visited[start]=1; tPath.push_back(start); dfs(start,endC,0,0,n); //cout<<start<<" "; for(int i=0; i<path.size(); i++) cout<<path[i]<<" "; cout<<minDis<<" "<<minCost; return 0; }
原文地址:https://www.cnblogs.com/zhanghaijie/p/10298358.html