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
题目大意:4个点,5条路,起点0,终点3
然后每条双向边的起始点,终点,长度,花费,
输出从起点到终点的路径,最短路径,最少花费。
思路:用dijstra计算最短路的时候用pre数组存结点前驱
dfs回溯路径,用vector存,然后倒序输出。
#include <stdio.h>
#include <string.h>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <iostream>
#define INF 0x3f3f3f3f
using namespace std;
int ma[505][505];
int cost[505][505];
int dis[505];//起点到结点的距离
int sum[505];//记录花费
int pre[505];//记录路径前驱
int vis[505];
int n,m,s,e;
vector<int> path;
void dfs(int x)
{
if(x==-1) return;
path.push_back(x);
x=pre[x];
dfs(x);
}
int main()
{
int i,j,next;
scanf("%d%d%d%d",&n,&m,&s,&e);
memset(ma,INF,sizeof ma);
memset(cost,INF,sizeof cost);
memset(dis,INF,sizeof dis);
memset(sum,INF,sizeof sum);
memset(pre,-1,sizeof pre);
memset(vis,0,sizeof vis);
for(i=0;i<m;i++)
{
int x,y,z,c;
scanf("%d%d%d%d",&x,&y,&z,&c);
ma[x][y]=ma[y][x]=z;
cost[x][y]=cost[y][x]=c;
}
sum[s]=0;
dis[s]=0;
for(i=0;i<n;i++)
{
int d=INF;
for(j=0;j<n;j++)
{
if(vis[j]==0&&dis[j]<d)
{
d=dis[j];
next=j;
}
}
vis[next]=1;
for(j=0;j<n;j++)
{
if(dis[j]>dis[next]+ma[next][j])
{
dis[j]=dis[next]+ma[next][j];
sum[j]=sum[next]+cost[next][j];
pre[j]=next;
}
else if(dis[j]==dis[next]+ma[next][j])
{
if(sum[j]>sum[next]+cost[next][j])
{
sum[j]=sum[next]+cost[next][j];
pre[j]=next;
}
}
}
}
dfs(e);
for(i=path.size()-1;i>=0;i--)
printf("%d ",path[i]);
printf("%d %d\n",dis[e],sum[e]);
}