题目概括:给两个城市点,求这两个点的最短路径,如果有若干条最短路径,则选择最便宜的那条。。显然单源有权图用Dijkstra算法,只不过有多了一重选择条件
#include<cstdio>
#define INFINITY 65535
const int maxn=510;
int dist[maxn], cost[maxn], E[maxn][maxn], C[maxn][maxn], collect[maxn];
int N, M, S, D;
int findMin(){
int minn=510, index=-1;
for(int i=0; i<N; i++){
if(collect[i]==0&&dist[i]<minn){
minn=dist[i];
index=i;
}
}
return index;
}
void Dijkstra(){
int v;
dist[S]=0;
collect[S]=1;
while(1){
v=findMin();//未被收录的dist最小值
if(v==-1)break;//找不到就返回-1,跳出循环
collect[v]=1;
for(int i=0; i<N; i++){
if(collect[i]==0&&E[v][i])//未被收录进去并且两结点有路径
if(dist[v]+E[v][i]<dist[i]){
dist[i]=dist[v]+E[v][i];
cost[i]=cost[v]+C[v][i];
}else if(dist[v]+E[v][i]==dist[i]&&cost[v]+C[v][i]<cost[i]){
cost[i]=cost[v]+C[v][i];
}
}
}
printf("%d %d", dist[D], cost[D]);
}
int main(){
scanf("%d%d%d%d", &N, &M, &S, &D);
int a, b;
for(int i=0; i<M; i++){
scanf("%d%d", &a, &b);
scanf("%d%d", &E[a][b], &C[a][b]);
E[b][a]=E[a][b]; C[b][a]=C[a][b];
}
for(int i=0; i<N; i++){
if(E[S][i]!=0){//两结点有路径
dist[i]=E[S][i];
cost[i]=C[S][i];
}else{
dist[i]=cost[i]=INFINITY;
}
}
Dijkstra();
return 0;
}