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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
较为经典的dijkstra
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int n,m,start,terminal;
int road[510][510];
bool visit[510];
int dist[510];
int fee[510];
int road_fee[510][510];
int path[510];
void Dijkstra(){
for(int z = 0; z < n; z++)
{
long long index = -1,maxnum = 0x3f3f3f3f;
for(int i = 0; i < n; i++){
if(!visit[i]&&dist[i] < maxnum)
{
index = i;
maxnum = dist[i];
}
}
if(index == -1)
break;
visit[index] = true;
for(int i = 0; i < n; i++){
if(!visit[i]&&road[index][i]!=0x3f3f3f3f){
if(dist[index]+road[index][i] < dist[i])
{
dist[i] = dist[index] + road[index][i];
path[i] = index;
fee[i] = fee[index] + road_fee[index][i];
}
else if(dist[index]+road[index][i] == dist[i]&&fee[i]>fee[index]+road_fee[index][i])
{
fee[i] = fee[index] + road_fee[index][i];
path[i] = index;
}
}
}
}
}
void printf_road(int v){
if(v==-1)
return;
printf_road(path[v]);
cout <<v << " ";
}
int main(){
cin >> n >> m >> start >> terminal;
memset(visit,false,sizeof(visit));
memset(dist,0x3f,sizeof(dist));
memset(road,0x3f,sizeof(road));
for(int i = 0; i < m; i++){
long long a,b,c,d;
cin >> a >> b >> c >> d;
road[a][b] = road[b][a] = c;
road_fee[a][b] = road_fee[b][a] = d;
}
dist[start] = 0;
fee[start] = 0;
path[start] = -1;
Dijkstra();
printf_road(terminal);
cout << dist[terminal] << " " << fee[terminal] <<endl;
return 0;
}