数据结构实验之图论七:驴友计划

数据结构实验之图论七:驴友计划
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic Discuss
Problem Description

做为一个资深驴友,小新有一张珍藏的自驾游线路图,图上详细的标注了全国各个城市之间的高速公路距离和公路收费情况,现在请你编写一个程序,找出一条出发地到目的地之间的最短路径,如果有多条路径最短,则输出过路费最少的一条路径。
Input

连续T组数据输入,每组输入数据的第一行给出四个正整数N,M,s,d,其中N(2 <= N <= 500)是城市数目,城市编号从0~N-1,M是城市间高速公路的条数,s是出发地的城市编号,d是目的地的城市编号;随后M行,每行给出一条高速公路的信息,表示城市1、城市2、高速公路长度、收费额,中间以空格间隔,数字均为整数且不超过500,输入数据均保证有解。
Output

在同一行中输出路径长度和收费总额,数据间用空格间隔。
Example Input

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

3 40
Hint

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>

typedef struct 
{
    int len;
    int cost;   
}node;
node map[550][550];
node low[550];
int visit[550];
int dijkstra(int n,int start)
{
    int mincost,minlen,pos = start;
    for(int i = 0;i<n;i++)
    {
        low[i].cost = map[pos][i].cost;
        low[i].len = map[pos][i].len;       
    } 
    visit[start] = 1;
    for(int i = 0;i<n-1;i++)
    {
        mincost = INT_MAX;
        minlen = INT_MAX;
        for(int j = 0;j<n;j++)
        {
            if(visit[j]==0&&(low[j].len<minlen||(low[j].len==minlen&&low[j].cost<mincost)))
            {
                minlen = low[j].len;
                mincost = low[j].cost;
                pos = j;
            }
        }
        visit[pos] = 1;
        for(int j = 0;j<n;j++)
        {
            if(map[pos][j].len!=INT_MAX&&low[pos].len + map[pos][j].len<low[j].len)
            {
                low[j].cost = low[pos].cost + map[pos][j].cost;
                low[j].len = low[pos].len + map[pos][j].len;
            }
            else if(map[pos][j].len!=INT_MAX&&(low[pos].len + map[pos][j].len == low[j].len)&&(low[pos].cost + map[pos][j].cost < low[j].cost))
            {
                low[j].cost = low[pos].cost + map[pos][j].cost;
                low[j].len = low[pos].len + map[pos][j].len;
            }
        } 
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,m,s,d;
        scanf("%d %d %d %d",&n,&m,&s,&d);
        for(int i = 0;i<n;i++)
        {
            for(int j = 0;j<n;j++)
            {
                map[i][j].cost = INT_MAX;
                map[i][j].len = INT_MAX;
            }
        }
        memset(visit,0,sizeof(visit));
        for(int i = 0;i<m;i++)
        {
            int a,b,c,d;
            scanf("%d %d %d %d",&a,&b,&c,&d);
            if(c<map[a][b].len||(map[a][b].len==c&&d<map[a][b].cost))
            {
                map[a][b].cost = d;
                map[a][b].len = c;
                map[b][a].cost =d;
                map[b][a].len = c;
            }
        }
        dijkstra(n,s);
        printf("%d %d\n",low[d].len,low[d].cost);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值