最短路模板(堆最佳化Dijkstra)(自用

Liyukio發表於2024-11-27
#include<iostream>
#include<vector> 
#include<queue> 
#include<cstring>

using namespace std;
const long long MAX = (1<<31) - 1;
const int N = 1e5 + 10;

vector<pair<int,int>>V[N];
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;
vector<int> dist (N,MAX);
bool vis[N];
void dijstra(int root) {
	dist[root] = 0;
	q.push({0,root});
	while(q.size()){
		auto a = q.top();q.pop();
		int w = a.first,v = a.second;
		if(vis[v]) continue;
		vis[v] = true;
		for(auto i:V[v]){
			int a = i.first,b = i.second;
			if(dist[a] > dist[v] + b){
				dist[a] = dist[v] + b;
				q.push({dist[a],a});
			}
		}
	}
}
int main(void){
	int n,m,s; cin>>n>>m>>s;
	for(int i = 1;i <= m;i ++){
		 int u,v,w; cin>>u>>v>>w;
		 V[u].push_back({v,w}); 
	}
	dijstra(s);
	for(int i = 1;i <= n;i ++) cout<<dist[i]<<" ";
	cout<<endl;
	return 0;
}

相關文章