Luo Gu [] P3385 [template] negative ring

Topic links: https://www.luogu.com.cn/problem/P3385

Interpretations: Bellman_ford forfeit ring, the reinforcing note data needs to judge whether the ring is connected to the negative point 1, a recording tmp [] is a bit connected to a recording.

#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e4+10;
int dis[maxn], tmp[maxn];
int from[maxn], to[maxn], cost[maxn];
int n, m, cnt;
void solve()
{
	cin >> n >> m;
	cnt = 1;
	for (int i = 1; i <= m; i++)
	{
		int a, b, c;
		cin >> a >> b >> c;
		from[cnt] = a;
		to[cnt] = b;
		cost[cnt] = c;
		cnt++;
		if (c >= 0)
		{
			from[cnt] = b;
			to[cnt] = a;
			cost[cnt] = c;
			cnt++;
		}
	}
	for (int i = 1; i <= n; i++)	dis[i] = inf, tmp[i] = 0;
	dis[1] = 0;
	tmp[1] = 1;
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= cnt; j++)
		{
			if (dis[to[j]] > cost[j] + dis[from[j]])
			{
				dis[to[j]] = cost[j] + dis[from[j]];
			}
			if (tmp[from[j]] == 1)
				tmp[to[j]] = 1;
		}
	}
	for (int i = 1; i <= cnt; i++)
	{
		if (dis[to[i]] > cost[i] + dis[from[i]]&&(tmp[from[i]] == 1 || tmp[to[i]] == 1))
		{
			cout << "YE5" << endl;
			return;
		}
	}
	cout << "N0" << endl;
	return;
}
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}

 

Published 119 original articles · won praise 20 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_40727946/article/details/103395742