单源最短路径
使用Dijkstra求解
#include<cstdio>
#include<algorithm>
using namespace std;
int N,M,S,D;
const int maxn=505;
const int INF=1e9;
int G[maxn][maxn];
int C[maxn][maxn];
int vis[maxn]={0};
int d[maxn];
int costs[maxn];
void Dijkstra(int s){
fill(d,d+maxn,INF);
fill(costs,costs+maxn,INF);
d[s]=0;
costs[s]=0;
for(int i=0;i<N;i++){
int Min = INF,u = -1;
for(int j=0;j<N;j++){
if(vis[j]==0 && d[j] < Min){
u=j;
Min=d[j];
}
}
if(u == -1) return;
vis[u]=1;
for(int v=0;v<N ;v++){ //以u为父节点,延伸出来的边
if(vis[v]==0 && G[u][v]!=INF ){
if( d[u] +G[u][v] < d[v]){
d[v]= G[u][v] + d[u];
costs[v]=costs[u]+C[u][v];
}else if(d[u] +G[u][v] == d[v] && costs[u] +C[u][v] < costs[v]){
costs[v]=costs[u]+C[u][v];
}
}
}
}
}
int main(){
int u,v,length,cost;
scanf("%d%d%d%d",&N,&M,&S,&D);
fill(G[0],G[0]+maxn*maxn,INF);
for(int i=0;i<M;i++){
scanf("%d%d%d%d",&u,&v,&length,&cost);
G[u][v]=length;
G[v][u]=length;
C[u][v]=cost;
C[v][u]=cost;
}
Dijkstra(S);
printf("%d %d\n",d[D],costs[D]);
return 0;
}