hdu2544(Bellman-ford)

本文介绍了一个使用C++实现的Bellman-Ford算法示例,该算法用于解决带负权边的最短路径问题。代码展示了如何构建图并进行松弛操作以找到从源点到所有其他点的最短路径。
<!-- lang: cpp -->
#include<iostream>
using namespace std;
struct edge
{
    int a,b,cost;
    edge *next;
    edge(){next=NULL;}
};
edge *h,*p;
int d[101],n,e;
void BellmanFord()
{
    int i;
    for(i=0;i<n-1;i++)
    {
        for(p=h;p!=NULL;p=p->next)
            if(d[p->b]>d[p->a]+p->cost)
                d[p->b]=d[p->a]+p->cost;
    }
}
int main()
{
    int i,tmpa,tmpb,tmpc;
    while(cin>>n>>e&&(n!=0||e!=0))
    {
        h=p=NULL;
        for(i=0;i<n;i++)
            d[i]=0xfffffff;
        d[0]=0;
        for(i=0;i<e;i++)
        {
            cin>>tmpa>>tmpb>>tmpc;
            h=new edge;
            h->a=tmpa-1;
            h->b=tmpb-1;
            h->cost=tmpc;
            h->next=p;
            p=h;
            h=new edge;
            h->a=tmpb-1;
            h->b=tmpa-1;
            h->cost=tmpc;
            h->next=p;
            p=h;
        }
        BellmanFord();
        cout<<d[n-1]<<endl;
    }
    return 0;
}

转载于:https://my.oschina.net/fzyz999/blog/143353

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值