SPFA 最短路

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
#define ElemType int
#define LIST_INIT_SIZE 10
#define LISTINCREMENT 2
#define inf 0x3f3f3f
struct A
{
    ll ed;
    ll power;
};
vector<A> v[20200];
queue <ll>q;
ll dis[101010];
ll vis[101010];
ll n,m;
void SPFA(ll s,ll n)
{
    memset(dis,inf,sizeof(dis));
    memset(vis,0,sizeof(vis));
    dis[s]=0;
    vis[s]=1;
    q.push(s);
    while(!q.empty())
    {
        ll u=q.front();
        q.pop();
        vis[u]=0;
        for(ll i=0;i<v[u].size();i++)
        {
            ll x=v[u][i].ed;
            ll y=v[u][i].power;
            if(dis[u]+y<dis[x])
            {
                dis[x]=dis[u]+y;
                if(vis[x]==0)
                {
                    q.push(x);
                    vis[x]=1;
                }
            }
        }
    }
    return ;
}
int main()
{
    cin>>n>>m;
    ll x,y,i,c;
    struct A t;
    for(i=0;i<m;i++)
    {
        cin>>x>>y>>c;
        t.ed=x;
        t.power=c;
        v[y].push_back(t);
        t.ed=y;
        t.power=c;
        v[x].push_back(t);
    }
    SPFA(0,n);
    for(i=1;i<n;i++)
        cout<<dis[i]<<endl;
}

原文地址:https://www.cnblogs.com/zcy19990813/p/9702685.html