用的spfa,在1,2,3,6节点上TLE
查看原帖
用的spfa,在1,2,3,6节点上TLE
1086574
Cgetierr楼主2023/10/2 15:53
#include<iostream>
using namespace std;
#include<algorithm>
#include<vector>
#include<climits>
#include<cstring>
#include<cmath>
#include<queue>
#define inf 0x3f3f3f3f
const int N = 1e5 + 10;
int d[N], cnt[N];
bool vis[N];
queue<int>q;
struct edge
{
	int v, w;
};
vector<edge>e[2 * N];
int n, m, s, a, b, c;

bool spfa(int s)
{
	for (int i = 0; i <= n; i++)
	{
		d[i] = inf;
	}
	d[s] = 0;
	vis[s] = 1;
	q.push(s);
	while (!q.empty())
	{
		int u = q.front();
		q.pop();
		vis[u] = 0;
		for (auto ed : e[u])
		{
			int v = ed.v;
			int w = ed.w;
			if (d[v] > d[u] + w)
			{
				d[v] = d[u] + w;
				cnt[v] = cnt[u] + 1;
				if (cnt[v] >= n)
				{
					return true;
				}
				if (!vis[v])
				{
					q.push(v);
					vis[v] = 1;
				}
			}
		}
	}
	return false;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> n >> m >> s;
	for (int i = 1; i <= m; i++)
	{
		cin >> a >> b >> c;
		e[a].push_back({ b,c });
	}
	if (!spfa(s))
	{
		for (int i = 1; i <= n; i++)
		{
			cout << d[i] << " ";
		}
	}

	return 0;
}
2023/10/2 15:53
加载中...