Problem Description
做爲一個資深驢友,小新有一張珍藏的自駕遊線路圖,圖上詳細的標註了全國各個城市之間的高速公路距離和公路收費情況,現在請你編寫一個程序,找出一條出發地到目的地之間的最短路徑,如果有多條路徑最短,則輸出過路費最少的一條路徑。
Input
連續T組數據輸入,每組輸入數據的第一行給出四個正整數N,M,s,d,其中N(2 <= N <= 500)是城市數目,城市編號從0~N-1,M是城市間高速公路的條數,s是出發地的城市編號,d是目的地的城市編號;隨後M行,每行給出一條高速公路的信息,表示城市1、城市2、高速公路長度、收費額,中間以空格間隔,數字均爲整數且不超過500,輸入數據均保證有解。
Output
在同一行中輸出路徑長度和收費總額,數據間用空格間隔。
Example Input
1
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
Example Output
3 40
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int e[1000][1000],m[1000][1000];
int book[1000],dis[1000],cost[1000];
int N,M,s,d;
int inf = 99999999;
void Dijkstra()
{
int i,j,k;
for(i=0;i<N;i++)
{
dis[i] = e[s][i];
cost[i] = m[s][i];
}
book[s] = 1;
for(i=1;i<=N-1;i++)
{
int minx1 = inf;
int minx2 = inf;
for(j=0;j<N;j++)
{
if((book[j] == 0 && dis[j] < minx1 )|| (book[j] == 0 && dis[j] == minx1 && cost[j]<minx2))
{
minx1 = dis[j];
minx2 = cost[j];
k = j;
}
}
book[k] = 1;
for(j = 0;j<N;j++)
{
if(e[k][j] < inf)
{
if((book[j] == 0 && dis[j] > dis[k] + e[k][j])||(book[j] == 0&&dis[j] == dis[k] + e[k][j]&&cost[j] > cost[k] + m[k][j] ))
{
dis[j] = dis[k] + e[k][j];
cost[j] = cost[k] + m[k][j];
}
}
}
}
printf("%d %d\n",dis[d],cost[d]);
}
int main()
{
int T;
int a,b,l,p;
scanf("%d",&T);
while(T--)
{
memset(book,0,sizeof(book));
scanf("%d%d%d%d",&N,&M,&s,&d);
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(i == j)
{
e[i][j] = 0;
m[i][j] = 0;
}
else
{
e[i][j] = inf;
m[i][j] = inf;
}
}
}
for(int i=1;i<=M;i++)
{
scanf("%d%d%d%d",&a,&b,&l,&p);
e[a][b] = e[b][a] = l;
m[a][b] = m[b][a] = p;
}
Dijkstra();
}
return 0;
}