Shortest SPFA template

// 
//   Dijkstra wives of brothers ℃ Shan .cpp
 //   algorithm
 // 
//   the Created by david.xu ON 2018/8/6.
 //   Copyright 2018 Qian leak? David.xu. All Rights Reserved.
 // When entering a team more than n times the loop negatively the BFS
 // fast: DFS point when a short circuit occurs twice in the most 

#include <stdio.h> 
#include <the cstdlib> 
#include <CString> 
#include <the cmath> 
#include <the iostream > 
#include <algorithm> 
#include <Queue> 
#include <Vector>
 #define MAXN 100010 the using namespace STD; int

 

 n,m,s,dis[maxn];
bool vis[maxn];

struct edge{
    int val,to;
};
vector<edge> e[maxn];

queue<int> q;

void SPFA()
{
    for(int i=1;i<=n;i++)
        dis[i]=1000000001;
    dis[s]=0;
    q.push(s);
    vis[s]=1;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(int i=0;i<e[x].size();i++)
        {
            int y=e[x][i].to;
            if(dis[x]+e[x][i].val<dis[y])
            {
                dis[y]=dis[x]+e[x][i].val;
                if(!vis[y])
                {
                    q.push(y);
                    vis[y]=1;
                }
            }
        }
        vis[x]=0;
    }
}

int main()
{
    scanf("%d%d%d",&n,&m,&s);
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        edge tmp;
        tmp.to=y;
        tmp.val=z;
        e[x].push_back(tmp);
    }
    SPFA();
    for(int i=1;i<=n;i++)
        printf("%d ",dis[i]);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Tidoblogs/p/11222319.html