dij、floyed与spfa
无优化spfa
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<deque>
#include<cstdlib>
#include<ctime>
#define dd double
#define ll long long
#define ull unsigned long long
#define N 500010
#define M number
using namespace std;
const ll INF=2147483647;
int n,m,s;
struct edge{
int to,w,next;
inline void readin(int to,int w,int next)
{
this->to=to;this->w=w;this->next=next;
}
};
edge li[N];
int tail,head[N];
ll d[N];bool vis[N];
inline void add(int from,int to,int w)
{
li[++tail].readin(to,w,head[from]);
head[from]=tail;
}
struct node{
int i;ll d;
node(int i,int d): i(i),d(d) {}
node() {}
};
queue<node> q;
inline void spfa(int s)
{
d[s]=0;
q.push(node(s,d[s]));
vis[s]=1;
while(!q.empty())
{
node now=q.front();q.pop();
vis[now.i]=0;
for(int k=head[now.i];k;k=li[k].next)
{
if(d[li[k].to]>d[now.i]+li[k].w)
{
d[li[k].to]=d[now.i]+li[k].w;
if(!vis[li[k].to]) vis[li[k].to]=1,q.push(node(li[k].to,d[li[k].to]));
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&s);
for(int i=1;i<=m;i++)
{
int from,to,w;
scanf("%d%d%d",&from,&to,&w);
add(from,to,w);
}
for(int i=1;i<=n;i++) d[i]=INF;
spfa(s);
for(int i=1;i<=n;i++) printf("%lld ",d[i]);
}
堆优化dij
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<deque>
#include<cstdlib>
#include<ctime>
#define dd double
#define ll long long
#define ull unsigned long long
#define N 300000
using namespace std;
const ll INF=0x3f3f3f3f;
struct edge{
int to,w,next;
inline void readin(int a,int b,int c)
{
to=a;w=b;next=c;
}
};
edge li[N];int head[N],tail;
inline void add(int from,int to,int w)
{
li[++tail].readin(to,w,head[from]);
head[from]=tail;
}
struct node{
int d,sum;
node() {}
node(int d,int sum): d(d),sum(sum) {}
};
node a[N/2+10];
struct cmp{
inline bool operator () (node a,node b)
{
return a.d>b.d;
}
};
priority_queue<node,vector<node>,cmp> q;
int n,m,s;
bool vis[N/2+10];
inline void dij(int s)
{
q.push(node(0,s));
while(!q.empty())
{
node now=q.top();q.pop();
if(vis[now.sum]) continue;
vis[now.sum]=1;
for(int k=head[now.sum];k;k=li[k].next)
{
int to=li[k].to;
if(a[to].d>a[now.sum].d+li[k].w)
{
a[to].d=a[now.sum].d+li[k].w;
q.push(a[to]);
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&s);
for(int i=1;i<=m;i++)
{
int from,to,w;
scanf("%d%d%d",&from,&to,&w);
add(from,to,w);
}
for(int i=1;i<=n;i++) a[i].d=INF,a[i].sum=i;
a[s].d=0;
dij(s);
for(int i=1;i<=n;i++) printf("%d ",a[i].d);
}
floyed
int d[N][N];
int main(){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int q=1;q<=n;q++)
if(d[j][p]>d[j][i]+d[i][q])
d[j][p]=d[j][i]+d[i][q];
}
其中 floyed作为多源最短路算法,可以用来传递闭包,或者是解决无向图最小环问题。