zoukankan      html  css  js  c++  java
  • spfa模板

    #include<bits/stdc++.h>
    using namespace std;
    #define ll long long
    const int N=10005,M=5e5+5;
    int head[N],ver[M],edge[M],Next[M],d[N];
    const int INF=0x7fffffff;
    queue<int>q;
    bool v[N];
    int n,m,s,tot;
    void add(int x,int y,int z)
    {
        ver[++tot]=y,edge[tot]=z,Next[tot]=head[x],head[x]=tot;
    }
    void spfa()
    {
        fill(d,d+n+1,INF);
        memset(v,0,sizeof(v));
        d[s]=0;v[s]=1;
        q.push(s);
        while(q.size())
        {
            int x=q.front();
            q.pop();
            v[x]=0;
            for(int i=head[x];i;i=Next[i])
            {
                int y=ver[i],z=edge[i];
                if(d[y]>d[x]+z)
                {
                    d[y]=d[x]+z;
                    if(!v[y])
                    {
                        q.push(y);
                        v[y]=1;
                    }
                }
            }
        }
    }
    int main()
    {
        
        cin>>n>>m>>s;
        for(int i=1;i<=m;i++)
        {
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            add(x,y,z);    
        }
        spfa();
        for(int i=1;i<=n;i++)
        {
            printf("%d ",d[i]);
        }
        return 0;
    }
  • 相关阅读:
    设计模式七大原则之单一职责原则
    机器学习入门与进阶
    Django之路
    Python编程之路
    Python练习1
    Docker入门与进阶
    运维相关
    Node.js(一)
    位运算
    双指针算法
  • 原文地址:https://www.cnblogs.com/hh13579/p/11385464.html
Copyright © 2011-2022 走看看