最短路板子 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});
            }
        }
    }
}
复制代码

 

posted @   摸鱼选手LLF  阅读(134)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示