最短路板子 spfa和djs

#include<bits/stdc++.h>
#define fi first
#define se second
#define io std::ios::sync_with_stdio(false)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const ll mod=1e9+7,INF = 0x3f3f3f3f;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll exgcd(ll a, ll b, ll &x, ll &y) {if(!b) {x = 1; y = 0; return a;}ll r = exgcd(b, a % b, x, y);ll tmp = x; x = y, y = tmp - a / b * y;return r;}
ll qpow(ll a,ll n){ll r=1%mod;for (a%=mod; n; a=a*a%mod,n>>=1)if(n&1)r=r*a%mod;return r;}
ll qpow(ll a,ll n,ll P){ll r=1%P;for (a%=P; n; a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll EX_BSGS(ll a,ll b,ll p){if(b == 1) return 0;map<ll,ll> pw;ll cnt = 0, t = 1, s, x, m;for(ll d = gcd(a, p); d != 1; d = gcd(a, p)){if(b % d) return -1;++cnt, b /= d, p /= d, t = 1LL * t * a / d % p;
if(b == t) return cnt;}s = b, m = sqrt(p) + 1;for(ll i = 0; i < m; ++i){pw[s] = i;s = 1LL * s * a % p;}x = qpow(a, m, p), s = t;for(ll i = 1; i <= m; ++i){s = 1LL * s * x % p;if(pw.count(s)) return i * m - pw[s] + cnt;
}return -1;} //拔山盖世!
const int maxn=1e3+10;
ll _next[maxn*2],head[maxn],tot,to[maxn*2];
ll li[maxn*2],w[maxn*2];
void add(ll x,ll y,ll ww)
{
_next[++tot]=head[x],head[x]=tot,to[tot]=y,w[tot]=ww;
//_next[++tot]=head[y],head[y]=tot,to[tot]=x;
}
int vis[maxn];
int d[maxn];
void spfa(int s)
{
    queue<int> que;
    memset(d,INF,sizeof(d));
    memset(vis,0,sizeof(vis));
    d[s]=0;
    vis[s]=1;
    que.push(s);
    while(que.size())
    {
        int u=que.front();
        que.pop();
        vis[u]=0;
        for(int i=head[u];i;i=_next[i])
        {
            int v=to[i];
            if(d[u]+w[i]<d[v])
            {
                d[v]=d[u]+w[i];
                if(!vis[v])
                {
                    que.push(v);
                    vis[v]=1;
                }
            }
        }
    }
}
void djs(int s)
{
    priority_queue<pii,vector<pii>,greater<pii> > que;
    memset(d,INF,sizeof(d));
    d[s]=0;
    que.push({0,s});
    while(que.size())
    {
        pii p=que.top();
        que.pop();
        int u=p.se;
        if(d[u]<p.fi) continue;
        for(int i=head[u];i;i=_next[i])
        {
            int v=to[i];
            if(d[v]>d[u]+w[i])
            {
                d[v]=d[u]+w[i];
                que.push({d[v],v});
            }
        }
    }
}
原文地址:https://www.cnblogs.com/acmLLF/p/13895475.html