spfa求助
查看原帖
spfa求助
929529
wym_2012楼主2024/1/19 21:21
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e3 + 9 , inf = 0x3f3f3f3f;
int t;
int n , m;
struct node{
	int to , val;
};
vector<node>v[maxn];
bool vis[maxn];
int num[maxn];
int dis[maxn];
bool spfa()
{
	memset(vis , false , sizeof(vis));
	memset(num , 0 , sizeof(num)); 
	memset(dis , inf , sizeof(dis));
	queue<int>q;
	q.push(1);
	dis[1] = 0;
	vis[1] = true;
	num[1]++;
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		if(num[u] >= n)
			return true;
		vis[u] = false;
		for(int i = 0; i < v[u].size(); i++)
		{
			int y = v[u][i].to , w = v[u][i].val;
			if(dis[y] > dis[u] + w)
			{
				dis[y] = dis[u] + w;
				q.push(y);
				vis[y] = true;
				num[y]++;
				if(num[y] >= n)
					return true;
			}
		}	
	}
	return false;
}
int main()
{
	cin >> t;
	while(t--)
	{
		for(int i = 1; i <= maxn; i++)
			v[i].clear(); 
		cin >> n >> m;
		while(m--)
		{
			int x , y , z;
			cin >> x >> y >> z;
			v[x].push_back({y , z});
			if(z >= 0) 
				v[y].push_back({x , z});
		}
		if(spfa())
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}

样例过subtask#1全wa

悬关

2024/1/19 21:21
加载中...