• 单源最短路径,spfa


    SPFA又是一个好东西,看代码吧qwq

    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    const int oo=2147483647;
    const int Maxn=500001;
    queue<int> q;
    
    int head[Maxn*2],nxt[Maxn*2],to[Maxn*2],w[Maxn*2];
    int n,m,id,a,b,c;
    int dist[Maxn];
    bool inq[Maxn];
    int cnt;
    
    void add(int u,int v,int c)//加边了呢
    {
        ++cnt;
        nxt[cnt]=head[u];
        head[u]=cnt;
        to[cnt]=v;
        w[cnt]=c;
    }
    
    int main()
    {
        memset(inq,false,sizeof(inq));
        cin>>n>>m>>id;
        for(int i=1; i<=m; i++)
            cin>>a>>b>>c,add(a,b,c);
        for(int i=1; i<=n; i++)
            dist[i]=oo;
        dist[id]=0;
        inq[id]=true;
        q.push(id);
        while(!q.empty()) {
            int u=q.front();
            q.pop();
            inq[u]=false;
            for(int v=head[u]; v; v=nxt[v]) {
                if(dist[to[v]]>dist[u]+w[v]) { //神奇的松弛操作了呢
                    dist[to[v]]=dist[u]+w[v];
                    if(inq[to[v]]==false) {
                        inq[to[v]]=true;
                        q.push(to[v]);
                    }
                }
            }
        }
        for(int i=1; i<=n; i++) //没了,挺简单的
            cout<<dist[i]<<' ';
        cout<<endl;
        return 0;
    }

    可以用双端队列deque奥,不用了,懒得改了呢,qwq

  • 相关阅读:
    BZOJ 3991 set维护dfs序
    BZOJ 4547 矩阵快速幂
    WERTYU | TEX Quotes
    高精度运算
    最大公约数和最小公倍数
    老鼠的旅行
    数据交换
    1136 A Delayed Palindrome
    1137 Final Grading
    1138 Postorder Traversal
  • 原文地址:https://www.cnblogs.com/Shen-Yu/p/9880459.html
Copyright © 2020-2023  润新知