1. 程式人生 > >優先佇列優化dijstra模板

優先佇列優化dijstra模板

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
typedef pair<int, int>pii;
struct cmp
{
	bool operator()(pii a, pii b) { return a.first > b.first; }
};
int n, m, s;
int to[200005], head[200005], nx[200005], va[200005],cnt,dis[100005];
void add(int u, int v, int w)
{
	to[++cnt] = v;
	va[cnt] = w;
	nx[cnt] = head[u];
	head[u] = cnt;
}
void dijstra(int s)
{
	for (int i = 1; i <= n; i++)dis[i] = 1e9+7;
	dis[s] = 0;
	priority_queue<pii, vector<pii>, cmp>q;
	q.push(make_pair(0, s));
	while (!q.empty())
	{
		pii u = q.top();
		q.pop();
		if (u.first > dis[u.second])continue;
		for (int i = head[u.second]; i; i = nx[i])
		{
			int j = to[i];
			if (dis[j] > u.first + va[i])
			{
				dis[j] = u.first + va[i];
				q.push(make_pair(dis[j], j));
			}
		}
	}
}
int main()
{
	while (cin >> n >> m >> s)
	{
		cnt = 0;
		while (m--)
		{
			int x, y, z;
			scanf("%d%d%d", &x, &y, &z);
			add(x, y, z);
		}
		dijstra(s);
		for (int i = 1; i <= n; i++)printf("%d ", dis[i]);
	}
}