1033 To Fill or Not to Fill (25 分)
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
题目大意:从起点到中终点最短路径的前提下求最小花费
思路:用dij算法在求最短路径时,当出现路径一样短时,比较路费的大小,如果更小,则更新path
解题代码:
#include<bits/stdc++.h>
using namespace std;
int n,m,s,d;
const int N = 1001;
const int INF = 0x3f3f3f3f;
int maze[N][N];
int dist[N];
int path[N]={0};
int vis[N]={0}; //该点是否被访问
int c[N]; //s点到所有点的路费
int costs[N][N]; //两点之间的路费
void dij(int s,int d)
{
for(int i=0;i<n;i++)
{
if(dist[i]<INF)
path[i]=s;
else path[i]=-1;
}
while(1)
{
int min=INF,v=-1;
for(int i=0;i<n;i++)
{
if(dist[i]<min&&!vis[i])
{
min=dist[i];
v=i;
}
}
if(v==-1)break;
vis[v]=1;
for(int i=0;i<n;i++)
{
if(!vis[i]&&dist[i]>dist[v]+maze[v][i])
{
dist[i]=dist[v]+maze[v][i];
c[i]=c[v]+costs[v][i];
path[i]=v;
}
else if(!vis[i]&&dist[i]==dist[v]+maze[v][i])
{
if(c[v]+costs[v][i]<c[i])
{
c[i]=c[v]+costs[v][i];
path[i]=v;
}
}
}
}
}
void dfs(int d)
{
if(d!=s)dfs(path[d]);
printf("%d ",d);
}
int main()
{
cin>>n>>m>>s>>d;
for(int i=0;i<n;i++)
dist[i]=INF;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
maze[i][j]=INF;
costs[i][j]=INF;
}
for(int i=1;i<=m;i++)
{
int x,y,dis,cost;
cin>>x>>y>>dis>>cost;
maze[x][y]=dis;
maze[y][x]=dis;
costs[x][y]=cost;
costs[y][x]=cost;
}
for(int i=0;i<n;i++)
{
dist[i]=maze[s][i];
c[i]=costs[s][i];
}
dij(s,d);
dfs(d);
cout<<dist[d]<<" "<<c[d];
}
出处:PTA甲级-1033