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
题意:给出图中每条边的距离以及花费,求出最短路径,如果有多条,求出最小化服的路径。
#include <iostream>
#include "vector"
using namespace std;
const int maxx = 510,INF=9999999;
int n,m,s,des,micost=INF,midistance=INF;
bool vis[maxx];
int g[maxx][maxx];
int d[maxx],cost[maxx][maxx];
vector<int> pre[maxx],path,tempath;
void dijkstra(int start){
fill(d,d+maxx,INF);
d[start] = 0;
for (int i = 0; i < n; ++i) {
int u=-1,MIN=INF;
for (int j = 0; j < n; ++j) {
if (!vis[j] && d[j] < MIN){
MIN = d[j];
u=j;
}
}
if (u==-1) return;
vis[u]= true;
for (int j = 0; j < n; ++j) {
if (!vis[j] && g[u][j] < INF){
if (d[u] + g[u][j] < d[j]){
d[j]=d[u]+g[u][j];
pre[j].clear();
pre[j].push_back(u);
} else if (d[u]+g[u][j]==d[j]){
pre[j].push_back(u);
}
}
}
}
}
void dfs(int start){
if (start==s){
tempath.push_back(start);
int totalcast=0,totallen=0;
for (int i = tempath.size()-1; i > 0; --i) {
int now = tempath[i],next=tempath[i-1];
totalcast += cost[now][next];
totallen += g[now][next];
}
if (totalcast < micost){
micost = totalcast;
midistance = totallen;
path = tempath;
}
tempath.pop_back();
return;
}
tempath.push_back(start);
for (int i = 0; i < pre[start].size(); ++i) {
dfs(pre[start][i]);
}
tempath.pop_back();
}
int main() {
cin>>n>>m>>s>>des;
fill(g[0],g[0]+maxx*maxx,INF);
for (int i = 0; i < m; ++i) {
int a,b,c,e;
cin>>a>>b>>c>>e;
g[a][b]=c;
g[b][a]=c;
cost[a][b]=e;
cost[b][a]=e;
}
dijkstra(s);
dfs(des);
for (int i = path.size()-1; i >=0 ; --i) {
cout<<path[i]<<" ";
}
cout<<midistance<<" "<<micost;
}
写dijkstra的时候都没有想每个变量代表啥了,之后还重新算了最小距离是多少,殊不知d数组存放的就是最小距离。