SPFA例题/模板

https://www.acwing.com/problem/content/1131/

 

#include<bits/stdc++.h>

#define fore(x,y,z) for(LL x=(y);x<=(z);x++)
#define forn(x,y,z) for(LL x=(y);x<(z);x++)
#define rofe(x,y,z) for(LL x=(y);x>=(z);x--)
#define rofn(x,y,z) for(LL x=(y);x>(z);x--)
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second

using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;

int n,m,s,t;
vector<int> adj[3000];
vector<int> cost[3000];
int dis[3000];
bool st[3000];
void SPFA()
{
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0;
    
    deque<int> que;
    que.push_back(s);
    st[s]=true;
    while(que.size())
    {
        int u=que.front();
        que.pop_front();
        st[u]=false;
        auto &nxts=adj[u];
        auto &costs=cost[u];
        int sz=nxts.size();
        for(int i=0;i<sz;i++)
        {
            if(dis[nxts[i]]>dis[u]+costs[i])
            {
                dis[nxts[i]]=dis[u]+costs[i];
                if(!st[nxts[i]])
                {
                    que.push_back(nxts[i]);
                    st[nxts[i]]=true;
                }
            }
        }
    }
}

void YD()
{
    cin>>n>>m>>s>>t;
    while(m--)
    {
        int a,b,c;cin>>a>>b>>c;
        adj[a].push_back(b);
        cost[a].push_back(c);
        adj[b].push_back(a);
        cost[b].push_back(c);
    }
    SPFA();
    cout<<dis[t]<<endl;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T=1;
    //cin >> T;
    while (T--)
    {
        YD();
    }
    return 0;
}
View Code

需要使用队列,以及st标记数组记录点是否在队列中

每一步出队需要更新距离

posted @ 2022-09-04 18:14  80k  阅读(71)  评论(0)    收藏  举报