局部变量在debug的时候有些编译器会默认初始值为0,但是执行的时候不这么做,所以导致debug的结果是对的,然而真正执行时结果不对,这个要注意,差点被坑了,
简单的Dijkstra的变形
#include<stdio.h>
#include<stdlib.h>
#define INIFINTE 32765
int distance[510],path[510],cst[510];
struct graph{
int distance;
int cost;
} vertix[510][510];
void Dij(int n,int s){
int v[510],i;
for(i = 0;i<n;i++){
v[i] = 0;
distance[i] = INIFINTE;
cst[i] = INIFINTE;
}
distance[s] = 0;
cst[s] = 0;
int j,closest,u;
for(i = 0;i<n;i++){
closest = INIFINTE;
for(j = 0;j<n;j++)
if(!v[j]&&distance[j]<closest){
closest = distance[j];
u = j;
}
v[u] = 1;
for(j = 0;j<n;j++)
if(vertix[u][j].distance)
if(distance[j]>distance[u] + vertix[u][j].distance){
distance[j] = distance[u] + vertix[u][j].distance;
cst[j] = cst[u] + vertix[u][j].cost;
path[j] = u;
}
else if(distance[j] == distance[u] + vertix[u][j].distance&&cst[j]>cst[u] + vertix[u][j].cost){
cst[j] = cst[u] + vertix[u][j].cost;
path[j] = u;
}
}
}
void PrintPath(int s,int d){
if(s == d){
printf("%d ",s);
return ;
}
else{
PrintPath(s,path[d]);
printf("%d ",d);
}
}
int main(){
int NumOfCity,NumOfWay,start,destination;
freopen("1.in","r",stdin);
scanf("%d%d%d%d",&NumOfCity,&NumOfWay,&start,&destination);
int i,j,k,cost,dis;
for(i = 0;i<NumOfCity;i++)
for(j = 0;j<NumOfCity;j++)
{
vertix[i][j].distance = INIFINTE;
vertix[i][j].cost = INIFINTE;
}
for(k = 0;k<NumOfWay;k++){
scanf("%d%d%d%d",&i,&j,&dis,&cost);
vertix[i][j].distance = vertix[j][i].distance = dis;
vertix[i][j].cost = vertix[j][i].cost = cost;
}
Dij(NumOfCity,start);
PrintPath(start,destination);
printf("%d %d\n",distance[destination],cst[destination]);
return 0;
}