求助 爆内存了 还能怎么优化空间呢
  • 板块CF20C Dijkstra?
  • 楼主Haii
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/8/8 18:05
  • 上次更新2023/10/27 16:25:11
查看原帖
求助 爆内存了 还能怎么优化空间呢
601916
Haii楼主2022/8/8 18:05
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>


typedef std::pair<int, int> PII;
typedef long long LL;
int const N = 100010;
int const M = 200010;
int e[M], ne[M], idx, h[N], st[N], w[M], cnt[N];//cnt存路径
int n, m;
LL d[N];

void add(int a, int b, int c)
{
	e[idx] = b, w[idx] = c;
	ne[idx] = h[a];
	h[a] = idx++;
}

void Dijkstra()
{
	cnt[1] = -1;
	for (int i = 1; i <= n; i++) d[i] = 9223372036854775806;
	d[1] = 0;

	std::priority_queue<PII, std::vector<PII>, std::greater<PII> > heap;
	heap.push({ 0,1 });
	while ((int)heap.size())
	{
		auto t = heap.top();
		heap.pop();
		int v = t.second, dis = t.first;
		if (st[v]) continue;
		st[v] = 1;
		for (int i = h[v]; i != -1; i = ne[i])
		{
			int j = e[i];
			if (d[j] > dis + w[i])
			{
				d[j] = dis + w[i];
				heap.push({ d[j],j });
				cnt[j] = v;
			}
		}
	}
}

int main()
{
	scanf("%d%d", &n, &m);
	memset(h, -1, sizeof h);
	while (m--)
	{
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		add(a, b, c), add(b, a, c);
	}
	Dijkstra();
	if (d[n] == 9223372036854775806) puts("-1");
	else
	{
		std::vector<int> ans;
		for (int i = n; i != -1; i = cnt[i]) ans.push_back(i);

		for (int i = (int)ans.size() - 1; i >= 0; i--) printf("%d ", ans[i]);
	}
	return 0;
}
2022/8/8 18:05
加载中...