当前位置: 首页 > 工具软件 > Dij > 使用案例 >

Dij堆优化板子

翟英达
2023-12-01

板子题:

Problem - 2544

板子:

struct Dij_Graph
{
	ll totPoint;
	ll edgeID;
	ll head[MXN];
	ll to[MXN << 1];
	ll val[MXN << 1];
	ll nxt[MXN << 1];
	ll dist[MXN];
	bool vis[MXN];
	heap<pll, vector<pll>, greater<pll>> he;
	void Init(ll n)
	{
		totPoint = n;
		edgeID = 0;
		FOR(i, 1, totPoint)
		head[i] = -1;
		return;
	}
	void AddEdge(ll u, ll v, ll w)
	{
		++edgeID;
		to[edgeID] = v;
		val[edgeID] = w;
		nxt[edgeID] = head[u];
		head[u] = edgeID;
		return;
	}
	void Build(ll s)
	{
		FOR(i, 1, totPoint)
		{
			dist[i] = LNF;
			vis[i] = false;
		}
		while (!he.empty())
			he.pop();
		dist[s] = 0;
		pll tmp;
		tmp.fir = 0;
		tmp.sec = s;
		he.push(tmp);
		while (!he.empty())
		{
			tmp = he.top();
			he.pop();
			ll id = tmp.sec;
			if (vis[id])
				continue;
			vis[id] = true;
			for (ll i = head[id]; i != -1; i = nxt[i])
			{
				ll j = to[i];
				if (vis[j])
					continue;
				if (dist[j] > dist[id] + val[i])
				{
					dist[j] = dist[id] + val[i];
					tmp.fir = dist[j];
					tmp.sec = j;
					he.push(tmp);
				}
			}
		}
		return;
	}
	ll Query(ll p)
	{
		if (p < 1 || p > totPoint || dist[p] == LNF)
			return -1;
		return dist[p];
	}
};
Dij_Graph g;

void Solve(void)
{
	ll n, m, s, t;
	cin >> n >> m >> s >> t;
	g.Init();
	while (m--)
	{
		ll u, v, w;
		cin >> u >> v >> w;
		g.AddEdge(u, v, w);
		g.AddEdge(v, u, w);
	}
	g.Build(s);
	cout << g.Query(t) << edl;
	return;
}

 类似资料: