07-图6 旅游规划 (25分)

单源最短路算法

#include
#define inf 260000
using namespace std;
struct node{
    int dist;
    int cost;
};

node Map[505][505];
int  dist[505],cost[505],n,m,s,d;

int main()
{
    scanf("%d %d %d %d",&n,&m,&s,&d);

    int i,j,a,b,dis,cos;
    for(i=0;ifor(j=0;jfor(i=0;i<m;i++){
        scanf("%d %d %d %d",&a,&b,&dis,&cos);
        Map[a][b].cost = Map[b][a].cost = cos;
        Map[a][b].dist = Map[b][a].dist = dis;
    }
    int cur=s,mindist=inf,mincost=inf,minnum;
    dist[s]=cost[s]=0;
    while(cur!=d){
        for(i=0;iif(dist[i]>dist[cur]+Map[cur][i].dist){
                dist[i] = dist[cur]+Map[cur][i].dist;
                cost[i] = cost[cur]+Map[cur][i].cost;
            }
            else{
                if(dist[i]==dist[cur]+Map[cur][i].dist&&cost[i]>cost[cur]+Map[cur][i].cost)
                    cost[i]=cost[cur]+Map[cur][i].cost;
            }
        }
        dist[cur] = cost[cur] = 0;
        mindist = mincost = inf;
        for(i=0;iif(dist[i]){//这个判断十分重要
                if(mindist>dist[i]){
                    mindist = dist[i];
                    mincost = cost[i];
                    minnum = i;
                }
                else{
                    if(mindist == dist[i]&&mincost>cost[i]){
                        mincost = cost[i];
                        minnum = i;
                    }
                }
            }
        }
        cur = minnum;
    }
    printf("%d %d\n",dist[d],cost[d]);

    return 0;
}








你可能感兴趣的:(PAT(A))