旅游规划

有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。

输入格式:

输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2)是城市的个数,顺便假设城市的编号为0~(N1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。

输出格式:

在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。

输入样例:

4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20

输出样例:

3 40

Floyd代码

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
#define MAX 1e9
struct 
{
    int l, s;
}a[500][500];
int main()
{
    int N, M, S, D,i,j,k,x,y,ll,ss;
    cin >> N >> M >> S >> D;
    for (i = 0; i < N;i++)
    for (j = 0; j < N; j++)
    {
        if (i == j)
        {
            a[i][j].l = 0;
            a[i][j].s = 0;
        }
        else
        {
            a[i][j].l = MAX;
                a[i][j].s = MAX;
        }
    }
    while (M--)
    {
        cin >> x >> y >> ll >> ss;
        a[x][y].l= ll;
        a[y][x].l = ll;
        a[y][x].s =ss;
        a[x][y].s = ss;
    }
    for (k = 0; k < N;k++)
    for (i = 0; i < N;i++)
    for (j = 0; j < N;j++)
    if (a[i][j].l>a[i][k].l + a[k][j].l || a[i][j].l == a[i][k].l + a[k][j].l&&a[i][j].s>a[i][k].s + a[k][j].s)
    {
        a[i][j].l = a[i][k].l+ a[k][j].l;
        a[i][j].s = a[i][k].s + a[k][j].s;
    }
    cout << a[S][D].l << " " << a[S][D].s;
}

dijkstra算法

#include <stdio.h>
#define MAX 100000
typedef struct
{
    int weight;
    int cost;
}graph;
int N,M,S,D;
graph g[500][500];
int dis[500];
int cost[500];
int flag[500];
void Dijkstra(int v)
{
    int min,i,j,pos;
    
    for(i=0;i<N;i++)
    {
        if(g[v][i].weight>0 )
        {
            dis[i]=g[v][i].weight;    
            cost[i]=g[v][i].cost;
        }        
    }
    flag[v]=1;
    for(i=0;i<N;i++)
    {
        min=MAX;
        pos=v;
        for(j=i;j<N;j++)
        {
            if(flag[j]!=1 &&dis[j]<min &&dis[j]>0)
            {
                min=dis[j];
                pos=j;
            }
        }
        flag[pos]=1;
    
        for(j=0;j<N;j++)
        {
            if(flag[j]!=1&&dis[pos]+g[pos][j].weight<dis[j] &&g[pos][j].weight>0&&dis[j]>0)
            {
                dis[j]=dis[pos]+g[pos][j].weight;
                cost[j]=cost[pos]+g[pos][j].cost;
            }
            else if(dis[pos]+g[pos][j].weight==dis[j] &&cost[j]>cost[pos]+g[pos][j].cost)
            {
                cost[j]=cost[pos]+g[pos][j].cost;
            }
        }
    }
    printf("%d %d
",dis[D],cost[D]);    
}
main()
{
    int a,b,l,c;
    int i,j;
    scanf("%d%d%d%d",&N,&M,&S,&D);
    for(i=0;i<M;i++)
    {
        scanf("%d%d%d%d",&a,&b,&l,&c);
        g[a][b].weight=g[b][a].weight=l;
        g[a][b].cost=g[b][a].cost=c;
    }
    Dijkstra(S);
}
原文地址:https://www.cnblogs.com/mayouyou/p/8670883.html