hdu 2544 最短路裸题 SPFA

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;

#define N 100010
#define INF 0x3f3f3f3f

int n,m,q;
struct Edge{
    int next,to,value;
}edge[N];
int head[N],tot;
bool exist[N];
int dis[N];
queue<int> Q;

inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

void Addedge(int u,int v,int w)
{
    tot++;edge[tot].next=head[u];edge[tot].to=v;edge[tot].value=w;head[u]=tot;
    tot++;edge[tot].next=head[v];edge[tot].to=u;edge[tot].value=w;head[v]=tot;
}

void SPFA()
{
    memset(dis,INF,sizeof(dis));
    dis[1]=0;exist[1]=1;
    Q.push(1);
    while(!Q.empty())
    {
        int now=Q.front();Q.pop();
        exist[now]=false;
        for(int i=head[now];i;i=edge[i].next)
        {
            int v=edge[i].to;
            if(dis[v]>dis[now]+edge[i].value)
            {
                dis[v]=dis[now]+edge[i].value;
                if(!exist[v])
                {
                    exist[v]=true;
                    Q.push(v);
                }
            }
        }
    }
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0)
            break;
        tot=0;
        memset(head,0,sizeof(head));
        for(int i=1;i<=m;i++)
        {
            int x=read(),y=read(),z=read();
            Addedge(x,y,z);
        }
        SPFA();
        cout<<dis[n]<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值