跳到正文

个人记录

Dijkstra+堆优化

Zzzsh约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年8月6日
收录
2025年12月12日
更新
2026年10月31日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
const int inf=2147483647;
int head[500000],next[500000],ver[500000],edge[500000];
int n,m,tot,s;
int dis[500000];
bool book[500000];
void add(int x,int y,int z)
{
	ver[++tot]=y;
	edge[tot]=z;
	next[tot]=head[x];
	head[x]=tot;
}
void dijkstra()
{
	priority_queue< pair<int,int> >q;
	for(int 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(book[t]) continue;
		book[t]=1;
		for(int i=head[t];i!=-1;i=next[i])
		{
			if(dis[ver[i]]>dis[t]+edge[i])
			{
				dis[ver[i]]=dis[t]+edge[i];
				q.push(make_pair(-dis[ver[i]],ver[i]));
			}
		}
	}
}
int main()
{
	int x,y,z;
	memset(head,-1,sizeof(head));
	memset(next,-1,sizeof(next));
	cin>>n>>m>>s;
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y>>z;
		add(x,y,z);
	}
	dijkstra();
	cout<<dis[1];
	for(int i=2;i<=n;i++)
		cout<<" "<<dis[i];
	return 0;
}
原文
抓取于
  1. Int_Main_

    $${\huge{M}^a_{rkd}o^{w_n}}$$