hdu2544(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;
}

你可能感兴趣的:(hdu2544(Bellman-ford))