hdu 3790 最短路径&最低费用 题目不难,但要注意重边

来源:互联网 发布:p2p下载软件推荐 编辑:程序博客网 时间:2024/05/01 09:39

最短路径问题

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 24838    Accepted Submission(s): 7408


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
 

Source
浙大计算机研究生复试上机考试-2010年
 

Recommend
notonlysuccess   |   We have carefully selected several similar problems for you:  1142 1385 2923 1875 2722 

最低费用的处理主要是在进行节点更新的时候,在两个节点之间距离相等的情况下,判断先前保存的路径费用是否高于当前更新后的路径费用,如果是的话,就说明有更低费用的路径


#include <stdio.h>#include <string.h>#define INF 500000000#define MAX 1010 int path[MAX][MAX] ,cost[MAX][MAX] , d[MAX] , c[MAX];bool visited[MAX];void dijkstra(int n , int src , int des){for(int i = 1 ; i <= n ; ++i ){d[i] = path[src][i] ;c[i] = cost[src][i] ;visited[i] = false ; }visited[src] = true ;for(int i = 1 ; i < n ; ++i){int minp = INF ,minc = INF , v ;for(int j = 1 ; j <= n ; ++j){if(!visited[j] && minp>d[j]){minp = d[j] ;minc = c[j] ;v = j ;} }if(minp == INF)break ;visited[v] = true ;for(int j = 1 ; j<=n ; ++j){if(!visited[j] && minp+path[v][j]<d[j]){d[j] = minp + path[v][j];c[j] = minc + cost[v][j];}else if(!visited[j] && minp+path[v][j]==d[j])  // this is important , while the distance  between two nodes is equal, you should choose the path with the lowest cost  {if(c[j] > minc+cost[v][j])c[j] = minc+cost[v][j];}}}}int main(){int n , m ;while(~scanf("%d%d",&n,&m)){if(n==0 && m==0){break;}for(int i = 1 ; i <= n ; ++i){for(int j = 1 ; j <= n ; ++j){cost[i][j] = INF ;path[i][j] = INF ;}}for(int i = 0 ; i < m ;++i){int a , b , l , p ;scanf("%d%d%d%d",&a,&b,&l,&p);if(path[a][b]>l) {path[a][b] = path[b][a] = l ;cost[a][b] = cost[b][a] = p ;}else if(path[a][b]==l && cost[a][b]>p){cost[a][b] = cost[b][a] = p ;}}int src , des ;scanf("%d%d",&src,&des) ;dijkstra(n , src , des);printf("%d %d\n",d[des],c[des]) ;}return 0 ;} 



1 0
原创粉丝点击