【模板】堆优化的dijkstra

生命算法,以防忘记

#include<bits/stdc++.h>
using namespace std;
int head[200005],dis[200005],n,m,s,f,g,w,l;
bool sign[200005];
struct node
{
int to,next,val;
} a[200005];
inline void in(int from,int to,int v)
{
a[++l].next=head[from];
a[l].to=to;
a[l].val=v;
head[from]=l;
}
priority_queue < pair<int,int> >q;
inline void dijkstra()
{
for(register int i=1; i<=n; i++)
dis[i]=2147483647;
dis[s]=0;
q.push(make_pair(0,s));
while(q.size())
{
int x=q.top().second;
q.pop();
if(sign[x])continue;
sign[x]=1;
for(register int i=head[x]; i; i=a[i].next)
if(dis[a[i].to]>dis[x]+a[i].val)
{
dis[a[i].to]=dis[x]+a[i].val;
q.push(make_pair(-dis[a[i].to],a[i].to));
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&s);
for(register int i=1; i<=m; i++)
{
scanf("%d%d%d",&f,&g,&w);
in(f,g,w);
}
dijkstra();
for(register int i=1; i<=n; i++)
printf("%d ",dis[i]);
return 0;
}
上一篇:学习笔记·堆优化$\mathscr{dijkstra}$


下一篇:洛谷 P4779 【dijkstra】+(堆优化)+(链式前向星) (模板题)