SPFA 模板

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int MAXN = 5000, MAXE = 21474836;
struct Edge
{
    int from, to, cost;
}es[MAXN << 2];
int first[MAXN << 2], next[MAXN << 2], tot, d[MAXN];
int t, c, te, ts;
bool used[MAXN];
queue < int > q; 

void build(int f, int t, int d)
{
    es[++tot].from = f;
    es[tot].to = t;
    es[tot].cost = d;
    next[tot] = first[f];
    first[f] = tot;
}

void spfa(int s)
{
    d[s] = 0;
    q.push(s);
    used[s] = 1;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        used[x] = 0;
        for(int i = first[x]; i != -1; i = next[i])
        {
            int u = es[i].to;
            if(d[u] > d[x] + es[i].cost)
            {
                d[u] = d[x] + es[i].cost;
                if(!used[u])
                {
                    q.push(u);
                    used[u] = 1;
                }
            }
        }
    }
}

int main()
{
    scanf("%d%d%d%d", &t, &c, &ts, &te);
    memset(first, -1, sizeof(first));
    for(int i = 1; i <= c; i++)
    {
        int rs, re, ci;
        scanf("%d%d%d", &rs, &re, &ci);
        build(rs, re, ci);
        build(re, rs, ci);
    }
    memset(d, 0x3f, sizeof(d));
    spfa(ts);
    cout<<d[te];
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值