P3371单源最短路径
  • 板块题目总版
  • 楼主panbaokun123
  • 当前回复2
  • 已保存回复2
  • 发布时间2023/1/27 21:51
  • 上次更新2023/10/24 02:54:10
查看原帖
P3371单源最短路径
824353
panbaokun123楼主2023/1/27 21:51

这里我用的堆优化dijkstra,wa了一个点,re了好几个点,不懂哪个地方出错了,有没有佬帮忙看看哪里有问题

#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <climits>
using namespace std;

//稀疏图---堆优化版dijkstra
typedef pair<int, int> PII;
const int INF = INT_MAX;
const int N = 10010;

int h[N], e[N], w[N], ne[N], idx;
int dist[N];

int n, m, s;

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

void dijkstra(vector<bool>& path)
{
	priority_queue<PII, vector<PII>, greater<PII>> heap;
	heap.push({ 0,s });

	while (!heap.empty())
	{
		int v = heap.top().second;
		heap.pop();

		if (path[v])
			continue;
		else
			path[v] = true;

		for (int i = h[v]; i != -1; i = ne[i])
		{
			int j = e[i];
			if (path[j])
				continue;
			if (dist[v] + w[i] < dist[j])
			{
				dist[j] = dist[v] + w[i];
				heap.push({ dist[j],j });
			}
		}
	}

}

int main()
{
	std::ios::sync_with_stdio(false);
	cin >> n >> m >> s;

	memset(h, -1, sizeof(h));
	idx = 0;
	memset(dist, 0x3f, sizeof(dist));
	dist[s] = 0;
	vector<bool> path(n + 1);

	while (m--)
	{
		int a, b, val;
		cin >> a >> b >> val;
		add(a, b, val);
	}

	dijkstra(path);
	for (int i = 1; i < n; i++)
	{
		if (dist[i] == 0x3f3f3f3f)
			cout << INT_MAX << " ";
		cout << dist[i] << " ";
	}
	cout << dist[n];

	return 0;
}
2023/1/27 21:51
加载中...