最短路spaf及dijkstra模板
spaf的双端队列优化:
#include<bits/stdc++.h> #define ll long long const ll maxn=210000; using namespace std; ll n,m,s,tot,link[maxn],dis[maxn],vis[maxn]; struct bian { ll y,v,next; }; bian a[maxn]; inline void add(ll x,ll y,ll v) { a[++tot].y=y; a[tot].v=v; a[tot].next=link[x]; link[x]=tot; } inline void spaf() { memset(dis,127,sizeof(dis)); deque<ll>q; q.push_front(s); dis[s]=0;vis[s]=1; while(!q.empty()) { ll x=q.front();q.pop_front();vis[x]=0; for(int i=link[x];i;i=a[i].next) { int y=a[i].y; if(dis[y]>dis[x]+a[i].v) { dis[y]=dis[x]+a[i].v; if(!vis[y]) { if(!q.size()||dis[y]>dis[q.front()]) q.push_back(y); else q.push_front(y); vis[y]=1; } } } } } int main() { freopen("1.in","r",stdin); cin>>n>>m>>s; for(int i=1;i<=m;i++) { ll x,y,v; cin>>x>>y>>v; add(x,y,v); } spaf(); for(int i=1;i<=n;i++) cout<<dis[i]<<' '; return 0; }
dijkstra:
inline void dij() { memset(dis,127,sizeof(dis)); dis[1]=0; q.push(make_pair(0,1)); while(!q.empty()) { ll x=q.top().second;q.pop(); if(vis[x]) continue; vis[x]=1; for(int i=link[x];i;i=a[i].next) { ll y=a[i].y; if(dis[y]>dis[x]+a[i].v) { dis[y]=dis[x]+a[i].v; q.push(make_pair(-dis[y],y)); } } } }
用dijkstra的最短路计数:
inline void dij() { memset(dis,127,sizeof(dis)); c[1]=1;dis[1]=0; q.push(make_pair(0,1)); while(!q.empty()) { ll x=q.top().second;q.pop(); if(vis[x]) continue; vis[x]=1; for(int i=link[x];i;i=a[i].next) { ll y=a[i].y; if(dis[y]==dis[x]+a[i].v) c[y]=c[x]+c[y]; if(dis[y]>dis[x]+a[i].v) { dis[y]=dis[x]+a[i].v; q.push(make_pair(-dis[y],y)); c[y]=c[x]; } } } }