关于spfa判负环用拓扑能不能AC
  • 板块灌水区
  • 楼主Link_Cut_Y
  • 当前回复4
  • 已保存回复4
  • 发布时间2022/1/24 17:54
  • 上次更新2023/10/28 11:17:41
查看原帖
关于spfa判负环用拓扑能不能AC
519384
Link_Cut_Y楼主2022/1/24 17:54

思路:首先拓扑排序,把所有的环(注意是环,不是负环)找出来,然后用dfsdfs遍历每个环,如果找到边权总和为负数的就输出 YesYes ,否则输出 NoNo

##Code:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 2010, M = 10010;
int h[N], e[M], ne[M], w[M], idx;
bool st[N];
int res, idu[N];
int n, m;

void add(int a, int b, int c)
{
	e[ ++ idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx, idu[b] ++ ;
}

void topsort()
{
	queue<int> q;
	for (int i = 1; i <= n; i ++ )
		if (!idu[i])
		{
			q.push(i);
			st[i] = true;
		}
		
	while (q.size())
	{
		int t = q.front();
		q.pop();
		for (int i = h[t]; i; i = ne[i])
		{
			int j = e[i];
			idu[j] -- ;
			if (!idu[j])
			{
				q.push(j);
				st[j] = true;
			}
		}
	}
}

void dfs(int u)
{
	for (int i = h[u]; i; i = ne[i])
	{
		int j = e[i];
		if (st[j]) continue;
		st[j] = true;
		res += w[i];
		dfs(j);
	}
}

int main()
{
	cin >> n >> m;
	
	for (int i = 1; i <= m; i ++ )
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}
	
	topsort();
	
	for (int i = 1; i <= n; i ++ )
		if (!st[i])
		{
			res = 0;
			dfs(i);
			cout << res << endl;
			if (res < 0)
			{
				puts("Yes");
				return 0;
			}
		}
			
	puts("No");
	
	return 0;
}
2022/1/24 17:54
加载中...