跳到正文

个人记录

P4779 【模板】单源最短路径(标准版)

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

文章信息

发布
2026年10月8日
收录
2026年10月8日
更新
2026年11月16日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,s;
int dis[100010],vis[100010];
struct Edge{
	int v,w;
};
vector<Edge> g[100010];
struct Node{
	int d,u;
	bool operator<(const Node& ot) const{
		return d>ot.d;
	}
};
void dijkstra(){
	memset(dis,0x3f,sizeof(dis));
	dis[s]=0;
	priority_queue<Node> q;
	q.push({0,s});
	while(!q.empty()){
		Node now=q.top();
		q.pop();
		int u=now.u;
		if(vis[u]) continue;
		vis[u]=1;
		for(auto e:g[u]){
			if(dis[e.v]>dis[u]+e.w){
				dis[e.v]=dis[u]+e.w;
				q.push({dis[e.v],e.v});
			}
		}
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m>>s;
	for(int i=1;i<=m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		g[u].push_back({v,w});
	}
	dijkstra();
	for(int i=1;i<=n;i++){
		cout<<dis[i]<<" ";
	}
	return 0;
}
原文