差分约束
2024年9月26日大约 2 分钟
差分约束
定义
差分约束系统 是一种特殊的
差分约束系统中的每个约束条件
注意到,如果
过程
设
具体实现
图判断负环,可以使用SPFA算法, 根据入队次数判断,如果入队次数超过n次(n为点数),则存在负权环
提示
注意,需要添加一个额外点,到所有点边权为0,防止不图不连通
关于判负环的细则,有洛谷大佬详解
简单总结要点:
- 不能按松弛次数判断,而是按入队次数
- 按入队次数可能存在爆int的情况
最高效的方式是判断最短路的长度,因为如果存在负环,那么负环一定会出现在最短路上,所以判断最短路是否超过n即可
模版
void spfa()
{
vector<int> dist(n, 0x3f3f3f3f);
dist[1] = 0;
vector<int> cnt(n, 0);
queue<int> que;
vector<int> visit(n,0);
// visit[0] = 1;
que.push(1);
while (!que.empty())
{
int now = que.front();
que.pop();
visit[now] = 0;
for (edge e : nodes[now].edges)
{
int end = e.to;
if (dist[end] > dist[now] + e.weight)
{
dist[end] = dist[now] + e.weight;
// cnt[end]++; // 这样判断存在bug
cnt[end] = cnt[now] + 1; // 最短路径长度
if (cnt[end] > n)
{
cout << "YES" << "\n";
return;
}
if (!visit[end])
{
que.push(end);
visit[end] = 1;
}
}
}
}
cout << "NO" << "\n";
}参考题:
