【图论】CODE[VS] 1557 热浪 (SPFA模板)

本文介绍了如何使用SPFA结合SLF优化解决异空间中给出的无向图最短路径问题,通过代码展示了解题过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:点击进入异空间


题意:求无向图的最短路 (尴尬,之前错误的代码还能AC??!!)

解法:SPFA加上SLF优化

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <queue>

const int maxn = 100005; 

using namespace std;

int tot;
int t,c,ts,te; 
int dist[maxn];
int head[maxn];
bool used[maxn];

struct node
{
    int f,t,c,next;
}es[maxn << 1];

inline void rd(int &x)
{
    scanf("%d",&x);
} 

inline void build(int x,int y,int z)
{
    tot++;
    es[tot].f = x;
    es[tot].t = y;
    es[tot].c = z;
    es[tot].next = head[x];
    head[x] = tot;
}

deque<int >q;

inline void spfa(int be)
{
    memset(dist,0x3f,sizeof(dist));
    while(!q.empty())q.pop_front();
    q.push_back(be);
    used[be] = true;
    dist[be] = 0;
    while(!q.empty())
    {
        int u = q.front();
        used[u] = false;
        q.pop_front();
        for(int i = head[u];i;i = es[i].next)
        {
            int v = es[i].t;
            if(dist[v] > dist[u] + es[i].c)
            {
                dist[v] = dist[u]+es[i].c;
                if(!used[v])
                {
                    if(dist[v] < dist[q.front()]) q.push_front(v);
                    else q.push_back(v);
                    used[v] = true; 
                }
            }
        }
    }
}

void init()
{
    memset(used,0,sizeof(used));
    memset(head,0,sizeof(head));
    tot = 0;
    return ;
}

int main()
{
    init();
    rd(t);rd(c);rd(ts);rd(te);
    for(int i = 1;i <= c;i++)
    {
        int x,y,z;
        rd(x);rd(y);rd(z);
        build(x,y,z);
        build(y,x,z);
    }
    spfa(ts);
    printf("%d\n",dist[te]);
return 0;
}

THE END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值