hdu 3790 最短路径问题

来源:互联网 发布:前瞻数据 编辑:程序博客网 时间:2024/06/08 08:48
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:  1217 1142 2680 1385 1598 
 


很好的一道最短路双向的制的题目。用典型的Dijkstra算法。
#include <iostream>#include <cstdio>using namespace std;const int INF=0x3f3f3f3f;int dist[1005];int cost[1005];bool vis[1005];int n,m;int start,end;struct note{    int d;//长度;    int p;//价格;} map[1005][1005];void dijkstra(int start,int end){    for(int i=1; i<=n; i++)    {        dist[i]=map[start][i].d;        cost[i]=map[start][i].p;        vis[i]=0;    }    dist[start]=0;    cost[start]=0;    vis[start]=true;    for(int i=2; i<=n; i++)    {        int min=INF;        int post;        for(int j=1; j<=n; j++)        {            if(!vis[j]&&dist[j]<min)            {                min=dist[j];                post=j;            }        }        vis[post]=true;        for(int j=1; j<=n; j++)        {            if(!vis[j]&&dist[j]>dist[post]+map[post][j].d)            {                dist[j]=dist[post]+map[post][j].d;                cost[j]=cost[post]+map[post][j].p;            }            else if(!vis[j]&&dist[j]==dist[post]+map[post][j].d)            {                if(cost[j]>cost[post]+map[post][j].p)                {                    cost[j]=cost[post]+map[post][j].p;                }            }        }    }}int main(){    while(scanf("%d%d",&n,&m))    {        if(n==0&&m==0)            break;        for(int i=1; i<1005; i++)            for(int j=1; j<1005; j++)            {                map[i][j].d=INF;                map[i][j].p=INF;            }        //cout<<"df"<<endl;        int a,b,distance,price;        //cout<<"df"<<endl;        for(int i=1; i<=m; i++)        {            //cin>>a>>b>>distance>>price;            scanf("%d%d%d%d",&a,&b,&distance,&price);            if(map[a][b].d>distance)            {                map[a][b].d=map[b][a].d=distance;                map[a][b].p=map[b][a].p=price;            }        }        cin>>start>>end;        dijkstra(start,end);        cout<<dist[end]<<" "<<cost[end]<<endl;    }    return 0;}


0 0
原创粉丝点击