TLE求助!!SPFA
查看原帖
TLE求助!!SPFA
504329
tfwy1214楼主2021/7/10 16:46
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;
const int N = 500010;
int h[N], idx, ne[N], e[N], w[N];
int n, m, s;
int dist[N];
int g[N],cnt;//记录路径
bool st[N];
void add(int a, int b, int c)
{
	e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void spfa(int s)
{
	memset(dist, 0x3f, sizeof dist);
	memset(st, false, sizeof st);
	dist[s] = 0;
	queue<int>q;
	q.push(s);
	st[s] = true;

	while (q.size())
	{
		int t = q.front();
		q.pop();
		st[t] = false;
		for (int i = h[t]; i != -1; i = ne[i])
		{
			int j = e[i];
			if (dist[j] > dist[t] + w[i])
			{
				dist[j] = dist[t] + w[i];
			}
			if (!st[j])
			{
				q.push(j);
				st[j] = true;
			}
		}
	}
}
int main()
{
	memset(h, -1, sizeof h);
	scanf("%d%d%d", &n, &m, &s);
	while (m--)
	{
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		add(a, b, c);
	}
	spfa(s);
	for (int i = 0; i < n; i++)
	{
		if (s == i)cout << 0 << ' ';
		else cout << dist[i] << ' ';
	}
	return 0;
}
2021/7/10 16:46
加载中...