【模板】最短路Dijkstra

模板題

#include<bits/stdc++.h>
using namespace std;
#define N 200005
struct mzls
{
	int nt,w,to;
}a[N];
struct node
{
	int x1,dis;
	node(){}
	node(int x,int y)
	{
		x1=x,dis=y;
	}
};
bool operator<(node x,node y)
{
	return x.dis>y.dis;
}
int head[N],cnt,dist[N],n,m,s;
bool vis[N];
inline void add(int x,int y,int z)
{
	a[cnt].to=y,a[cnt].w=z,a[cnt].nt=head[x],head[x]=cnt++;
}
inline void dij(int s)
{
	memset(vis,0,sizeof(vis));
	memset(dist,0x3f,sizeof(dist));
	dist[s]=0;
	priority_queue<node>que;
	que.push(node(s,0));
	while(!que.empty())
	{
		node ml=que.top();
		que.pop();
		int x=ml.x1,d=ml.dis;
		if(vis[x])
			continue;
		vis[x]=1;
		for(int i=head[x];i!=-1;i=a[i].nt)
		{
			int v=a[i].to,ct=a[i].w;
			if(d+ct<dist[v])
				dist[v]=d+ct,
				que.push(node(v,d+ct));
		}
	}
}
int main()
{
	memset(head,-1,sizeof(head));
	scanf("%d%d%d",&n,&m,&s);
	for(int i=1;i<=m;i++)
	{
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z);
	}
	dij(s);
	for(int i=1;i<=n;i++)
		printf("%d ",dist[i]);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章