单源最短路径(可有负边权)(spfa)新模板

和原板子区别不大,更符合我的代码习惯

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 2e5+5;
int n, m, head[maxn], s, num = -1, dis[maxn];
bool exist[maxn];
struct mint
{
    int nxt, v, w;    
}e[maxn];
inline void add(int u, int v, int w)
{
    e[++num].nxt = head[u];
    e[num].v = v;
    e[num].w = w;
    head[u] = num;    
}
inline void spfa()
{
    memset(dis,0x3f,sizeof(dis));
    memset(head,-1,sizeof(head));
    dis[1] = 0;
    exist[1] = true;
    queue<int> q;
    q.push(1);
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        for(int i = head[u];~i;i = e[i].nxt)
        {
            int v = e[i].v;
            if(dis[v] > dis[u] + e[i].w)
            {
                dis[v] = dis[u] + e[i].w;
                if(!exist[v])
                {
                    q.push(v);
                    exist[v] = true;    
                }
            }    
        }
        exist[u] = false;
    }
}
int main()
{
    scanf("%d%d%d", &n, &m, &s);
    int a, b, c;
    for(int i = 1;i <= m;++i)
    {
        scanf("%d%d%d", &a, &b, &c);
        add(a,b,c);    
    }
    spfa();
    for(int i = 1;i <= n;++i)
    {
        printf("%d ", dis[i]);    
    }
    return 0;
}    

 

上一篇:Activity class {package/class} does not exist


下一篇:Trie树(1)模板+例题