单源最短路狄克斯特拉 + 链式前向星 + 堆 优化
作者:互联网
#include<bits/stdc++.h>
#include<queue>
using namespace std;
const int maxn = 1e6;
const int INF = (1<<31 -1);
int head[maxn],dis[maxn],vis[maxn],n,m,s,cnt;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >q;//优先队列的写法stl中的结构体pair
//链式前向星存储图
struct node
{
int to,w,next;
}e[maxn];
void add(int u, int v, int w)
{
e[++cnt].w = w;
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt;
}
void dijkstra()
{
int i;
for(i = 1; i<=n; i++)
dis[i] = INF;
dis[s] = 0;
q.push(make_pair(0,s));
while(!q.empty())
{
int t = q.top().second;
q.pop();
if(vis[t]==1) continue;
vis[t] = 1;
for( i = head[t]; i; i = e[i].next )
{
if(dis[e[i].to] > dis[t] + e[i].w)
{
dis[e[i].to] = dis[t] + e[i].w;
q.push(make_pair(dis[e[i].to],e[i].to));
}
}
}
}
int main()
{
int u,v,w;
cin>>n>>m>>s;
for(int i=0; i<m; i++)
{
cin>>u>>v>>w;
add(u,v,w);
}
dijkstra();
for(int i = 1; i<=n; i++)
{
if(i!=1) cout<<" ";
cout<<dis[i];
}
cout<<endl;
return 0;
}
标签:cnt,狄克,cin,int,单源,next,head,前向星,dis 来源: https://blog.csdn.net/Wuko666/article/details/112547067