SPFA差分约束系统全TLE
查看原帖
SPFA差分约束系统全TLE
116495
GMU_QinYuCheng楼主2021/10/31 13:34
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>

using namespace std;

const int N = 5010;

int n,m;
int h[N], ne[N], e[N], w[N], idx;//邻接表 
int dist[N], cnt[N];
bool st[N];
int q[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], 
h[a] = idx++;
}
bool spfa()
{
	memset(dist, 0x3f, sizeof dist);
	dist[0] = 0;
	int  hh = 0, tt = 1;
	q[0] = 0;
	st[0] = true;
	while(hh != tt)
{
	int t = q[hh ++];
	if(hh == N) hh = 0;
	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[tt++] = j;
			 if(tt == N) tt = 0;
			 st[j] = true;
			}
			}
		}
	}
	return false;
}
int main()
{
cin >> n >> m;
	
while(m --)
{
int a, b, c;
scanf("%d%d%d",&a, &b, &c);
add(b, a, c);
}
	
for(int i = 1; i <= n; i ++) add(0, i, 0);
	
if(spfa()) puts("NO");
else 
{
for(int i = 1; i <= n; i++) cout << dist[i] << " ";
}
	
return 0;
}
2021/10/31 13:34
加载中...