其他分享
首页 > 其他分享> > 差分约束

差分约束

作者:互联网

https://www.luogu.com.cn/problem/P5960

给出一组包含 \(m\) 个不等式,有 \(n\) 个未知数的形如:

\[\begin{cases} x_{c_1}-x_{c'_1}\leq y_1 \\x_{c_2}-x_{c'_2} \leq y_2 \\ \cdots\\ x_{c_m} - x_{c'_m}\leq y_m\end{cases} \]

的不等式组,求任意一组满足这个不等式组的解。若无解,输出 "NO"。

#include <bits/stdc++.h>
using namespace std;
#define LL int
const int N = 5e3 + 10;
struct edge{
	LL u, v, w;
}e[N];
LL n, m, d[N];
void bellman_ford(){
	memset(d, 0x3f, sizeof d);
	d[1] = 0;
	for (int i = 1; i < n; i ++ )
		for (int j = 0; j < m; j ++ )
			d[e[j].v] = min(d[e[j].v], d[e[j].u] + e[j].w);
	for (int i = 0; i < m; i ++ )
		if (d[e[i].v] > d[e[i].u] + e[i].w){
			cout << "NO\n";
			return;
		}
	for (int i = 1; i <= n; i ++ )
		cout << d[i] << " \n"[i == n];
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	cin >> n >> m;
	for (int i = 0; i < m; i ++ ){
		LL u, v, w;
		cin >> v >> u >> w;
		e[i] = {u, v, w};
	}
	bellman_ford();
	return 0;
}

标签:不等式,leq,int,LL,差分,约束,++,bellman
来源: https://www.cnblogs.com/Hamine/p/16428936.html