📚【模板】差分约束

差分约束可以用来为一组有约束关系的变量找最小/大解。

比如:

\[\large\begin{aligned} x_1-x_0 \le 2\\ x_2-x_1 \le 4\\ x_2-x_0 \le 3 \end{aligned}\]

我们可以这样建图:

graph LR A(($x_0$)); B(($x_1$)); C(($x_2$)); A --2--> B B --4--> C A --3--> C

然后从\(x_0\)开始跑最路,就得到了方程的一组非负最解。

有时得用SPFA,要判负环(无解)。但一般情况下,直接进行Dijkstra就好了。(毕竟有一些出题人喜欢卡嘛……)

当然遇到其他约束时,我们也可以转化为小于或等于这个约束:

  1. \(\large x_1-x_0 < a \implies x_1-x_0 \le a-1\)

  2. \(\large x_0-x_1 \ge a \implies x_1-x_0 \le -a\)

  3. \(\large x_1-x_0 = a \implies x_1-x_0 \le a \And x_0-x_1 \le -a\)

  4. \(\large x_1 = x_0 \implies x_1-x_0 = 0\)然后回到3

当然,求最大值就按\(\le\),跑最短路;
否则跑最长路。

posted @ 2022-08-01 10:16  bikuhiku  阅读(21)  评论(0编辑  收藏  举报