SPFA
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int M=500010;
const int N=100010;
struct E {int to,nxt,w;}edge[M];
queue<int>q;
bool vis[N];
int idx[N],tot=1;
int n,m,s,t,dis[N];
void addedge(int from,int to,int w){
edge[tot].to=to;edge[tot].w=w;edge[tot].nxt=idx[from];idx[from]=tot++;
}
void SPFA(){
q.push(s);vis[s]=1;
memset(dis,127,sizeof(dis));
dis[s]=0;
while(!q.empty()){
int x=q.front();q.pop();
for(int t=idx[x];t;t=edge[t].nxt){
E e=edge[t];
if(dis[e.to]>dis[x]+e.w){
dis[e.to]=dis[x]+e.w;
if(!vis[e.to]){
vis[e.to]=1;
q.push(e.to);
}
}
}
vis[x]=0;
}
}
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
scanf("%d%d%d%d",&n,&m,&s,&t);
for(int i=1;i<=m;i++) {
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
addedge(x,y,w);
}
SPFA();
printf("%d\n",dis[t]);
return 0;
}
Dijkstra+优先级队列
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int N=100010;
const int M=500010;
struct E {int to,nxt,w;}edge[M];
struct P {
int d,x;
bool operator < (const P& p) const { return p.d<d; }
}tmp;
priority_queue<P>Q;
bool vis[N];
int dis[N];
int tot=1,idx[N];
int s,t,n,m;
void addedge(int from,int to,int w){
edge[tot].to=to;edge[tot].w=w;edge[tot].nxt=idx[from];idx[from]=tot++;
}
void dijkstra(){
memset(dis,127,sizeof(dis));
memset(vis,0,sizeof(vis));
tmp.d=0,tmp.x=s;
dis[s]=0;
Q.push(tmp);
while(!Q.empty()){
P p=Q.top();Q.pop();
int x=p.x;int d=p.d;
if(vis[x]) continue;vis[x]=1;
for(int t=idx[x];t;t=edge[t].nxt){
E e=edge[t];
if(d+e.w<dis[e.to]){
dis[e.to]=d+e.w;
tmp.d=dis[e.to],tmp.x=e.to;
Q.push(tmp);
}
}
}
}
int main(){
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
scanf("%d%d%d%d",&n,&m,&s,&t);
for(int i=1;i<=m;i++){
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
addedge(x,y,w);
}
dijkstra();
printf("%d\n",dis[t]);
return 0;
}