Dijkstra 堆优化

注意 不用vis[]判断

直接在 did结构体里面写operator <

写cmp的话要超时!!!

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=(1<<31)-1;
const int N=5e5;
struct Graph{
	ll nxt,to,val;
}edge[N<<1];
ll n,m,s;
int head[N],cnt;
void add(int u,int v,int w)
{
	cnt++;
	edge[cnt].to=v;
	edge[cnt].nxt=head[u];
	edge[cnt].val=w;
	head[u]=cnt;
}
ll dis[N];
struct did{
	int u,d;
	bool operator <(const did& t)const {
		return t.d<d;
	}
};
int vis[N];
priority_queue<did>q;
void dijkstra()
{
	for(int i=1;i<=n;i++)dis[i]=inf;
	dis[s]=0;
	q.push({s,0});
	vis[s]=1;
	while(!q.empty())
	{
		did tmp=q.top();
		q.pop();
		ll u=tmp.u,d=tmp.d;
		if(dis[u]!=d)continue;
		for(int i=head[u];i;i=edge[i].nxt)
		{
			ll v=edge[i].to;
			ll w=edge[i].val;
			if(dis[u]+w<dis[v])
			{
				dis[v]=dis[u]+w;
				q.push({v,dis[v]});
			}
		}
	}
}
signed main()
{
	ios::sync_with_stdio(false);
	cin>>n>>m>>s;
	for(int i=1;i<=m;i++)
	{
		ll u,v,w;
		cin>>u>>v>>w;
		add(u,v,w);
	}
	dijkstra();
	for(int i=1;i<=n;i++)
		cout<<dis[i]<<" ";cout<<"\n";
	return 0;
}
posted @ 2023-02-24 20:34  N0zoM1z0  阅读(243)  评论(0编辑  收藏  举报