HDU 3790最短路径问题 dijikstra算法

//赛码网 3790
*
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1
3 2
1 2 5 6
2 3 4 5
1 3
0 0
输出 一行有两个数, 最短距离及其花费。
9 11
*/

#include<iostream>
using namespace std;
const int INFINITY = 0xffffff;
const int MAX = 1000+10;
int n,m;
int Dist[MAX][MAX],Cost[MAX][MAX];
int min_dist,min_cost;
int beg,endd;

void dijikstra()
{
    int i,j;
    bool visit[MAX];
    int dist[MAX];
    int cost[MAX];
    int min,tempv;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
            dist[j] = Dist[beg][j];
            cost[j] = Cost[beg][j];
            visit[j] = false;
        }
    }
    dist[beg] = 0;
    visit[beg] = true;
    //cost[beg] = 0;
    for(i=0;i<m;i++)
    {
        //找最短的一条路
        min = INFINITY;
        tempv = beg;
        for(j=1;j<=n;j++)
        {
            if(!visit[j] && min>dist[j])
            {
                tempv = j;
                min = dist[j];

            }
        }
        visit[tempv] = true;
        for(j=1;j<=n;j++)
        {
            if(!visit[j] && min + Dist[tempv][j] < dist[j])
            {
                dist[j] = min+Dist[tempv][j];
                cost[j] = cost[tempv] + Cost[tempv][j];
            }
            else if(!visit[j] && min + Dist[tempv][j] == dist[j])
            {
                if(cost[j]>cost[tempv] + Cost[tempv][j])
                    cost[j] = cost[tempv]+Cost[tempv][j];
            }
        }
        if(visit[endd])
        {
            min_dist = dist[endd];
            min_cost = cost[endd];
            return;
        }
    }
    min_cost = cost[endd];
    min_dist = dist[endd];
    return;
}
int main()
{
    int a,b,d,p;
    int i,j;
    while(scanf("%d%d",&n,&m)) //需要注意这里,最好用scanf,不要用cin
    {
        if(n==0 && m==0)
            break;
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                Dist[i][j] = Dist[j][i]= INFINITY;
                Cost[i][j] =Cost[j][i] = INFINITY;              
            }
        }
        for(i=0;i<m;i++)
        {
            scanf("%d%d%d%d",&a,&b,&d,&p);
            if(Dist[a][b]>d)
            {
                Dist[a][b] = Dist[b][a] = d;
                Cost[a][b] = Cost[b][a] = p;
            }           
        }
        scanf("%d%d",&beg,&endd);
        dijikstra();
        printf("%d %d\n",min_dist,min_cost);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值