HDU3790:最短路径问题(Dijkstra)

来源:互联网 发布:天锐数据安全软件 编辑:程序博客网 时间:2024/05/16 10:32
Problem Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
 

Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
 

Output
输出 一行有两个数, 最短距离及其花费。
 

Sample Input
3 21 2 5 62 3 4 51 30 0
 

Sample Output
9 11


 

看题目名字就知道是最短路了- -

依然是Dijkstra模板,只是要统计时间和路程两个东西罢了

 

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int inf = 1<<30;int n,m;int map_len[1005][1005],map_time[1005][1005];int vis[1005],cost_len[1005],cost_time[1005];void Dijkstra(int s,int e){    int i,j,min,pos;    memset(vis,0,sizeof(vis));    cost_len[s] = 0;    cost_time[s] = 0;    vis[s] = 1;    for(i = 0; i<n; i++)    {        cost_len[i] = map_len[s][i];        cost_time[i] = map_time[s][i];    }    for(i = 1; i<n; i++)    {        min = inf;        for(j = 0; j<n; j++)        {            if(cost_len[j]<min && !vis[j])            {                pos = j;                min = cost_len[j];            }        }        vis[pos] = 1;        for(j = 0; j<n; j++)        {            if(cost_len[pos]+map_len[pos][j]<cost_len[j] && !vis[j])            {                cost_len[j] = cost_len[pos]+map_len[pos][j];                cost_time[j] = cost_time[pos]+map_time[pos][j];            }            else if(cost_len[pos]+map_len[pos][j]==cost_len[j] && !vis[j])//路程相同的情况下找时间少的            {                if(cost_time[pos]+map_time[pos][j]<cost_time[j])                {                    cost_time[j] = cost_time[pos]+map_time[pos][j];                }            }        }    }}int main(){    int s,e,len,time;    int i,j;    while(~scanf("%d%d",&n,&m),n+m)    {        for(i = 0; i<1005; i++)        {            for(j = 0; j<1005; j++)                map_len[i][j] = map_time[i][j] = inf;            map_len[i][i] = map_time[i][i] = 0;        }        while(m--)        {            scanf("%d%d%d%d",&s,&e,&len,&time);            s--;            e--;            if(len<map_len[s][e])            {                map_len[s][e] = map_len[e][s] = len;                map_time[s][e] = map_time[e][s] = time;            }        }        scanf("%d%d",&s,&e);        s--;        e--;        Dijkstra(s,e);        printf("%d %d\n",cost_len[e],cost_time[e]);    }    return 0;}


 

原创粉丝点击