10分求助
查看原帖
10分求助
1093410
shuanhao楼主2024/8/29 16:26
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;

const int N = 10010;
int n, m;
int h[N], e[N], w[N], ne[N], idx;
bool st[N];
int dist[N];
int cnt[N];

void add(int a, int b, int c)
{
	ne[idx] = h[a];
	e[idx] = b;
	w[idx] = c;
	h[a] = idx++;
}
bool spfa()
{
	memset(dist, 0x3f3f, sizeof(dist));
	memset(cnt, 0, sizeof(cnt));
	queue<int>q;
	dist[1] = 0;
	q.push(1);
	st[1] = 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];
				cnt[j] = cnt[t] + 1;
				if (cnt[j] >= n)return true;
				if (!st[j])
				{
					q.push(j);
					st[j] = true;
				}
			}
		}
	}
	return false;
}
int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		memset(h, -1, sizeof(h));
		cin >> n >> m;
		for (int i = 0; i < m; i++)
		{
			int a, b, c;
			cin >> a >> b >> c;
			if (c >= 0)
			{
				add(a, b, c);
				add(b, a, c);
			}
			else add(a, b, c);
		}
		if (spfa())
			cout << "YES" << endl;
		else cout << "NO" << endl;
	}
	return 0;
}
2024/8/29 16:26
加载中...