

//法1:已知起点终点->单源最短路径
//有权图的单源最短路径:Dijkstra的变形
#include <iostream>
#define MAXN 520
#define INFINITY 65535
using namespace std;
int G[MAXN][MAXN];int P[MAXN][MAXN];
int N,M,S,D;
void CreateG(){
cin>>N>>M>>S>>D;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
G[i][j]=INFINITY;
P[i][j]=INFINITY;
}
}
int v1,v2,l,p;
for(int i=0;i<M;i++){
cin>>v1>>v2>>l>>p;
G[v1][v2]=l;
G[v2][v1]=l;
P[v1][v2]=p;
P[v2][v1]=p;
}
}
int dist[MAXN];int cost[MAXN];int path[MAXN];
int collected[MAXN];
int FindMin(){
//按距离找最小
int minDist=INFINITY,minId=-1;
for(int i=0;i<N;i++){
if(!collected[i]){
if(dist[i]<minDist){
minDist=dist[i];
minId=i;
}
}
}
return minId;
}
void Dijkstra(){
//dist、cost初始化
//path在本题中并不需要
fill(dist,dist+N,INFINITY);
fill(cost,cost+N,INFINITY);
fill(path,path+N,INFINITY);
dist[S]=0;
cost[S]=0;
while(1){
int V=FindMin();
if(V==-1) break;
collected[V]=1;
for(int j=0;j<N;j++){
if(!collected[j] && G[V][j]!=INFINITY){
if(dist[V]+G[V][j]<dist[j]){
dist[j]=dist[V]+G[V][j];
path[j]=V;
//1:如果按距离更新:cost跟着dist一起更新
cost[j]=cost[V]+P[V][j];
}else if((dist[V]+G[V][j] == dist[j]) && (cost[V]+P[V][j]<cost[j])){
cost[j]=cost[V]+P[V][j];
path[j]=V;
//2:如果距离相同,按价格更新,cost单独更新
}
}
}
}
}
int main(){
CreateG();
Dijkstra();
cout<<dist[D]<<" "<<cost[D];
return 0;
}
//法2:使用通用的Floyd写法,同样可以解决
//就是显然慢很多
#include <iostream>
#define MAXN 510
#define W_INFINITY 510
using namespace std;
int G[MAXN][MAXN];int P[MAXN][MAXN];
int nv,ne;
int S,D;
void CreateG(){
cin>>nv>>ne>>S>>D;
for(int i=0;i<nv;i++){
for(int j=0;j<nv;j++){
G[i][j]=W_INFINITY;P[i][j]=W_INFINITY;
if(i==j){
G[i][j]=0;
P[i][j]=0;
}
}
}
int v1,v2,w,p;
for(int i=0;i<ne;i++){
cin>>v1>>v2>>w>>p;
G[v1][v2]=w;
G[v2][v1]=w;
P[v1][v2]=p;
P[v2][v1]=p;
}
}
int dist[MAXN][MAXN];
int pric[MAXN][MAXN];
void Floyd(){
for(int i=0;i<nv;i++){
for(int j=0;j<nv;j++){
dist[i][j]=G[i][j];
pric[i][j]=P[i][j];
}
}
for(int k=0;k<nv;k++){
for(int i=0;i<nv;i++){
for(int j=0;j<nv;j++){
if(dist[i][k]+dist[k][j]<dist[i][j]){
dist[i][j]=dist[i][k]+dist[k][j];
pric[i][j]=pric[i][k]+pric[k][j];
}else if(dist[i][k]+dist[k][j]==dist[i][j]){
if(pric[i][k]+pric[k][j]<pric[i][j]){
pric[i][j]=pric[i][k]+pric[k][j];
}
}
}
}
}
}
int main(){
CreateG();
Floyd();
cout<<dist[S][D]<<" "<<pric[S][D];
system("pause");
return 0;
}
1609

被折叠的 条评论
为什么被折叠?



