裸的最短路。
SPFA:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long LL;
const LL INF=200000000000000000ll;
const int SIZE=100010;
int head[SIZE],nxt[SIZE],tot=0;
struct edge{
int t;
LL d;
}l[SIZE];
void build(int f,int t,LL d)
{
l[++tot].t=t;
l[tot].d=d;
nxt[tot]=head[f];
head[f]=tot;
}
bool use[SIZE];
LL dist[SIZE];
deque<int> q;
int n;
LL spfa(int s)
{
for(int i=1;i<=n;i++) dist[i]=INF;
dist[s]=0;
use[s]=1;
q.push_front(s);
while(q.size())
{
int f=q.front(); q.pop_front();
use[f]=0;
for(int i=head[f];i;i=nxt[i])
{
int v=l[i].t;
if(dist[v]>dist[f]+l[i].d)
{
dist[v]=dist[f]+l[i].d;
if(!use[v])
{
use[v]=1;
if(q.empty()) q.push_front(v);
else
{
if(dist[q.front()]<dist[v]) q.push_back(v);
else q.push_front(v);
}
}
}
}
}
if(dist[n]==INF) return -1;
return dist[n];
}
int main()
{
int m;
scanf("%d%d",&n,&m);
while(m--)
{
int a,b;
LL c;
scanf("%d%d%lld",&a,&b,&c);
build(a,b,c);
}
printf("%lld",spfa(1));
return 0;
}
dijkstra:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long LL;
const LL INF=200000000000000000ll;
const int SIZE=100010;
int head[SIZE],nxt[SIZE],tot=0;
struct edge{
int t;
LL d;
}l[SIZE];
void build(int f,int t,LL d)
{
l[++tot].t=t;
l[tot].d=d;
nxt[tot]=head[f];
head[f]=tot;
}
bool vis[SIZE];
LL dist[SIZE];
struct Heap{
int u; LL d;
Heap(int a,LL b):u(a),d(b){}
};
priority_queue<Heap> q;
bool operator <(Heap a,Heap b)
{
return a.d>b.d;
}
int n;
LL dij(int s)
{
for(int i=1;i<=n;i++) dist[i]=INF;
dist[s]=0;
q.push(Heap(s,0));
while(q.size())
{
int f=q.top().u; q.pop();
if(vis[f]) continue;
vis[f]=1;
for(int i=head[f];i;i=nxt[i])
{
int v=l[i].t;
if(dist[v]>dist[f]+l[i].d)
{
dist[v]=dist[f]+l[i].d;
q.push(Heap(v,dist[v]));
}
}
}
if(dist[n]==INF) return -1;
return dist[n];
}
int main()
{
int m;
scanf("%d%d",&n,&m);
while(m--)
{
int a,b;
LL c;
scanf("%d%d%lld",&a,&b,&c);
build(a,b,c);
}
printf("%lld",dij(1));
return 0;
}