堆优化的dijkstra模板

#include <bits/stdc++.h>

using namespace std;

#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
typedef pair<int, int> PII;
const int N = 1e6 + 10;

int n, m, dis[N], vis[N];
vector<pair<int, int> > G[N];

void dijkstra() {
	memset(dis, 0x3f, sizeof dis);
	dis[1] = 0;
	priority_queue<PII, vector<PII>, greater<PII>> heap;
	heap.push({0, 1});
	while (!heap.empty()) {
		auto t = heap.top();
		heap.pop();
		int ver = t.second, distance = t.first;
		if (vis[ver]) continue;
		vis[ver] = true;
		for (int i = 0; i < G[ver].size(); i++) {
			int j = G[ver][i].first;
			int w = G[ver][i].second;
			if (dis[j] > distance + w) {
				dis[j] = distance + w;
				heap.push({dis[j], j});
			}
		} 
	}
}


int main() {
	cin >> n >> m;
	while (m--) {
		int x, y, z;
		cin >> x >> y >> z;
		G[x].push_back(make_pair(y, z));
	}
	dijkstra();
	if (dis[n] == 0x3f3f3f3f)
		cout << -1;
	else
		cout << dis[n];
	
	
	return 0;
}

猜你喜欢

转载自www.cnblogs.com/all-taker/p/12910208.html