差分约束

· · 个人记录

差分约束

前两天学了差分约束,总结一下。

前置芝士:最短路/最长路(SPFA 或 Bellman-Ford)

引入

现在有一个 n 元一次不等式组(假设共有 m 条不等式),需要你判断这个不等式组是否有解。若有解,给出一组合法的解。

解法

假设这 n 个变量为 x_{1 \sim n},每一条不等式为 x_{u_{i}} - x_{v_{i}} \leqslant y_{i}(1 \leqslant i \leqslant m),现在,我们浅推一下式子。

x_{u_{i}} - x_{v_{i}} \leqslant y_{i} x_{u_{i}} \leqslant x_{v_{i}} + y_{i}

我们就把不等式化成了 c \leqslant a + b 的形式,观察一下,可以发现它就是三角形不等式。

更进一步的,若我们令这个三角形的三个顶点为 A,B,C,用距离公式来代替边长,那么就可以变为 dist(A, B) \leqslant dist(A, C) + dist(C, B)。

接下来应该就很明显了吧,我们可以不用将 A,B,C 一定看作某个三角形的三个顶点,而是把它们看作一张图的三个节点,而这个三角形不等式就是图的最短路中边的松弛条件。

回到题目中来,我们的问题变成了如何把 x_{u_{i}},x_{v_{i}},y_{i} 这些条件转化成图的信息再求最短路。

联系最短路的松弛条件,我们可以将 x_{u_{i}} 和 x_{v_{i}} 看作图中节点到源点的最短路经长度,而 y_{i} 是节点 v_{i} 到 节点 u_{i} 的边权。(如果这里理解不了的话可以对着最短路代码想想)。

然后就是连边(以 v_{i} 为起点,u_{i} 为终点,y_{i} 为边权的有向边),最短路。

什么时候无解呢?

假设有三个不等式:

\begin{cases} x \leqslant y + w_{1}\\ y \leqslant z + w_{2}\\ z \leqslant x + w_{3} \end{cases}

(其中的 w_{1} + w_{2} + w_{3} 为负数)

我们可以化简一下(以 x 为例):

x \leqslant y + w_{1} \leqslant z + w_{1} + w_{2} \leqslant x + w_{1} + w_{2} + w_{3} 0 \leqslant w_{1} + w_{2} + w_{3} < 0 0 < 0

矛盾,故无解。

而上面这种情况(w_{1} + w_{2} + w_{3} < 0)对应到图中就是出现了负环。

如果没有出现负环,一定有解吗?

首先,如果没有负环,那么原图肯定存在最短路,也就是我们求出了 dist_{i} 的值。

若我们将 dist_{u_{i}} 和 dist_{v_{i}} 的值代入原不等式。

dist_{u_{i}} \leqslant dist_{v_{i}} + y_{i}

假设这时无解(也就是不符合不等式),那么此时的情况就是:

dist_{u_{i}} > dist_{v_{i}} + y_{i}

回到图中,我们在建图时连接了以 v_{i} 为起点,u_{i} 为终点,y_{i} 为边权的有向边,也就是遍历到节点 v_{i} 时会进行 dist_{u_{i}} \leqslant dist_{v_{i}} + y_{i} 的松弛操作判断,进行松弛操作后一定可以保证 dist_{u_{i}} \leqslant dist_{v_{i}} + y_{i},与假设条件矛盾,故假设不成立。

所以不存在负环时原不等式组一定有解。

可能出现的问题

建图后若原图是由若干个互不相关的子图构成时,该如何处理。解决方法也很简单,建立一个超级源点(比如 0)再向每个点连边就行了。

但是这样做又会引出另一个问题,如果按照题目的条件来连边,节点 0 不是边的起点怎么办?我们重新推式子:

x_{u_{i}} - x_{v_{i}} \leqslant y_{i} x_{u_{i}} - y_{i} \leqslant x_{v_{i}}

此时连的边就是以 u_{i} 为起点,v_{i} 为终点,-y_{i} 为边权的有向边,而最短路也变成了最长路(具体证明可以参照以上对最短路解法的证明)。

如果这样连边,起点和终点正好对调了,也就可以将节点 0 从终点转变为起点了。

另一个小问题,若题目对 x_{i} 有单独的要求(如 x_{i} \geqslant 0)而最短路求出的 dist_{i} < 0 怎么办?

注意到不等式是两个变量的差值与另一个常量的关系,只需要保持差值不变就行。

具体来说,将所有的 dist_{i} 同时加上一个数 add 即可。

一些细节

总结

我认为差分约束系统的题属于思维难度较大而代码难度较小的题,所以重点在于能否设计出正确的,高效的连边方式,求解方式。

题目

练习题以及题解。

差分约束算法(模板题)

就是引入中提到的情况, 注意超级源点的连边方式。

我们可以假设超级源点的值是一个极小值,即 x_{i} \geqslant x_{0}(1 \leqslant i \leqslant n),从节点 0 向节点 i 连接长度为 0 的有向边即可。

用最短路求解。

Code:

#pragma GCC diagnostic error "-std=c++11"
#include <bits/stdc++.h>
namespace VividCycle {
    #include <bits/stdc++.h>
    #define getchar gc
    #define putchar pc
    #define fu(i, l, r) for(int i = l; i <= r; ++i)
    #define fd(i, l, r) for(int i = l; i >= r; --i)
    using namespace std;
    typedef long long ll;
    typedef unsigned long long ull;
    static char buffer[1 << 20 | 1]; static int outp = -1;
    void flush() {fwrite(buffer, 1, outp + 1, stdout), outp = -1;}
    void pc(const char& ch) {if(outp == (1 << 20)) flush(); buffer[++outp] = ch;}
    char gc() {static char ibuf[1 << 20], *p1 = ibuf, *p2 = ibuf; return p1 == p2 && (p2 = (p1 = ibuf) + fread(ibuf, 1, 1000010, stdin), p1 == p2) ? -1 : *p1++;}
    template<typename T> void read(T& x) {x = 0; int f = 1; char ch = getchar(); while(ch < '0' || ch > '9') f *= ((ch == '-') ? -1 : 1), ch = getchar(); while(ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); x *= f;}
    template<typename T, typename ...Args> void read(T& x, Args& ...args) {read(x), read(args...);}
    void write(const char& ch) {putchar(ch);} void write(const char s[]) {int len = strlen(s) - 1; fu(i, 0, len) putchar(s[i]);} void write(char s[]) {int len = strlen(s) - 1; fu(i, 0, len) putchar(s[i]);}
    template<typename T> void write(T x) {static char obuf[1 << 8]; static int p; p = 0; if(x < 0) x *= (putchar('-'), -1); if(!x) {putchar('0'); return;} while(x) obuf[++p] = x % 10 ^ 48, x /= 10; while(p) putchar(obuf[p--]);}
    template<typename T, typename ...Args> void write(T x, Args ...args) {write(x), write(args...);}
}
using namespace VividCycle;
int n, m, u, v, w, cnt[5001], dis[5001];
vector< pair<int, int> > g[5001];
queue<int> q;
int main() {
    read(n, m);
    while(m--) {
        read(v, u, w);
        g[u].push_back(make_pair(v, w));
    }
    fu(i, 1, n) g[0].push_back(make_pair(i, 0));
    memset(dis, 0x3f, sizeof(dis));
    dis[0] = 0;
    q.push(0);
    while(!q.empty()) {
        u = q.front();
        q.pop();
        ++cnt[u];
        if(cnt[u] >= n) return 0 & puts("NO");
        for(const auto& i : g[u]) {
            if(dis[u] + i.second < dis[i.first]) {
                dis[i.first] = dis[u] + i.second;
                q.push(i.first);
            }
        }
    }
    fu(i, 1, n) write(dis[i], ' ');
    flush();
    return 0;
}

Wannafly挑战赛9 E 组一组

一道比较难的题,我到现在还是 \color{#f4a460}\texttt{TLE 17/100},读者可以先跳过这一部分。

我自认为我的做法没有错,有好心人也可以来帮帮我。

首先二进制拆分,以下的讨论皆基于 x_{i} 的某一位上。

接着是转化,用 sum_{i} 表示 x_{1 \sim i} 共有多少个 1。

若结果为 0,则 sum_{r_{i}} - sum_{l_{i} - 1} = 0。

若结果为 1,则 sum_{r_{i}} - sum_{l_{i} - 1} \geqslant 1。

若结果为 0,则 sum_{r_{i}} - sum_{l_{i} - 1} < r_{i} - l_{i} + 1。

若结果为 1,则 sum_{r_{i}} - sum_{l_{i} - 1} = r_{i} - l_{i} + 1。

对每一个 l_{i} - 1 和 r_{i} 连边即可。

而对于每一个二进制位,其值要么为 0 要么为 1,所以又有:

0 \leqslant sum_{i} - sum_{i - 1} \leqslant 1(1 \leqslant i \leqslant n)

连边后跑最长路。

Code:

#pragma GCC optimize(2)
#pragma GCC diagnostic error "-std=c++11"
#include <bits/stdc++.h>
#define getchar gc
#define putchar pc
#define fu(i, l, r) for(int i = l; i <= r; ++i)
#define fd(i, l, r) for(int i = l; i >= r; --i)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
static char buffer[1 << 20 | 1]; static int outp = -1;
void flush() {fwrite(buffer, 1, outp + 1, stdout), outp = -1;}
void pc(const char& ch) {if(outp == (1 << 20)) flush(); buffer[++outp] = ch;}
char gc() {static char ibuf[1 << 20], *p1 = ibuf, *p2 = ibuf; return p1 == p2 && (p2 = (p1 = ibuf) + fread(ibuf, 1, 1000010, stdin), p1 == p2) ? -1 : *p1++;}
template<typename T> void read(T& x) {x = 0; int f = 1; char ch = getchar(); while(ch < '0' || ch > '9') f *= ((ch == '-') ? -1 : 1), ch = getchar(); while(ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); x *= f;}
template<typename T, typename ...Args> void read(T& x, Args& ...args) {read(x), read(args...);}
void write(const char& ch) {putchar(ch);} void write(const char s[]) {int len = strlen(s) - 1; fu(i, 0, len) putchar(s[i]);} void write(char s[]) {int len = strlen(s) - 1; fu(i, 0, len) putchar(s[i]);}
template<typename T> void write(T x) {static char obuf[1 << 8]; static int p; p = 0; if(x < 0) x *= (putchar('-'), -1); if(!x) {putchar('0'); return;} while(x) obuf[++p] = x % 10 ^ 48, x /= 10; while(p) putchar(obuf[p--]);}
template<typename T, typename ...Args> void write(T x, Args ...args) {write(x), write(args...);}
int n, m, u, v, op[100001], l[100001], r[100001], x[100001], ans[100001], sum[100001], qwq[100001];
bool vis[100001];
vector< pair<int, int> > g[100001];
stack<int> q;
int main() {
    read(n, m);
    fu(i, 1, m) {
        read(op[i], l[i], r[i], x[i]);
        --l[i];
    }
    fu(p, 0, 19) {
        fu(i, 0, n) {
            sum[i] = 0x8f8f8f8f;
            qwq[i] = 0;
            g[i].clear();
        }
        fu(i, 1, n) {
            g[i - 1].push_back(make_pair(i, 0));
            g[i].push_back(make_pair(i - 1, -1));
        }
        fu(i, 1, m) {
            if(op[i] & 1) {//|
                if((x[i] >> p) & 1) {
                    g[l[i]].push_back(make_pair(r[i], 1));
                }
                else {
                    g[l[i]].push_back(make_pair(r[i], 0));
                    g[r[i]].push_back(make_pair(l[i], 0));
                }
            }
            else {//&
                if((x[i] >> p) & 1) {
                    g[l[i]].push_back(make_pair(r[i], r[i] - l[i]));
                    g[r[i]].push_back(make_pair(l[i], l[i] - r[i]));
                    ++qwq[l[i] + 1], --qwq[r[i] + 1];
                }
                else {
                    g[l[i]].push_back(make_pair(r[i], 0));
                    g[r[i]].push_back(make_pair(l[i], l[i] - r[i] + 1));
                }
            }
        }
        fu(i, 1, n) qwq[i] += qwq[i - 1];
        fu(i, 1, n) qwq[i] = (qwq[i] ? 1 : 0);
        fu(i, 1, n) qwq[i] += qwq[i - 1];
        fu(i, 1, n) {
            g[0].push_back(make_pair(i, qwq[i]));
        }
        sum[0] = 0;
        q.push(0);
        while(!q.empty()) {
            u = q.top();
            q.pop();
            vis[u] = false;
            for(const auto& i : g[u]) {
                if(sum[i.first] < sum[u] + i.second) {
                    sum[i.first] = sum[u] + i.second;
                    if(!vis[i.first]) {
                        vis[i.first] = true;
                        q.push(i.first);
                    }
                }
            }
        }
        fu(i, 1, n) ans[i] |= ((sum[i] - sum[i - 1]) << p);
    }
    fu(i, 1, n) write(ans[i], ' ');
    flush();
    return 0;
}

Layout排队布局/排队布局

正常推式子:

dist_{B} - dist_{A} \leqslant D \Rightarrow dist_{B} \leqslant dist_{A} + D dist_{B} - dist_{A} \geqslant D \Rightarrow dist_{A} \leqslant dist_{B} - D

注意题面中奶牛排在队伍中的顺序和它们的编号是相同的,也就是说奶牛的相对位置是确定的(或者说,编号大的奶牛一定会在编号小的奶牛的位置上或者后面)。

就可以得到以下隐藏条件:

dist_{i} - dist_{i - 1} \geqslant 0 \Rightarrow dist_{i - 1} \leqslant dist_{i} (1 \leqslant i \leqslant n)

超级源点的不等式:

dist_{i} - dist_{0} \geqslant 0 \Rightarrow dist_{0} \leqslant dist_{i} (1 \leqslant i \leqslant n)

(以上两个其实是重复的)

Code:

#pragma GCC diagnostic error "-std=c++11"
#include <bits/stdc++.h>
namespace VividCycle {
    #include <bits/stdc++.h>
    #define getchar gc
    #define putchar pc
    #define fu(i, l, r) for(int i = l; i <= r; ++i)
    #define fd(i, l, r) for(int i = l; i >= r; --i)
    using namespace std;
    typedef long long ll;
    typedef unsigned long long ull;
    static char buffer[1 << 20 | 1]; static int outp = -1;
    void flush() {fwrite(buffer, 1, outp + 1, stdout), outp = -1;}
    void pc(const char& ch) {if(outp == (1 << 20)) flush(); buffer[++outp] = ch;}
    char gc() {static char ibuf[1 << 20], *p1 = ibuf, *p2 = ibuf; return p1 == p2 && (p2 = (p1 = ibuf) + fread(ibuf, 1, 1000010, stdin), p1 == p2) ? -1 : *p1++;}
    template<typename T> void read(T& x) {x = 0; int f = 1; char ch = getchar(); while(ch < '0' || ch > '9') f *= ((ch == '-') ? -1 : 1), ch = getchar(); while(ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); x *= f;}
    template<typename T, typename ...Args> void read(T& x, Args& ...args) {read(x), read(args...);}
    void write(const char& ch) {putchar(ch);} void write(const char s[]) {int len = strlen(s) - 1; fu(i, 0, len) putchar(s[i]);} void write(char s[]) {int len = strlen(s) - 1; fu(i, 0, len) putchar(s[i]);}
    template<typename T> void write(T x) {static char obuf[1 << 8]; static int p; p = 0; if(x < 0) x *= (putchar('-'), -1); if(!x) {putchar('0'); return;} while(x) obuf[++p] = x % 10 ^ 48, x /= 10; while(p) putchar(obuf[p--]);}
    template<typename T, typename ...Args> void write(T x, Args ...args) {write(x), write(args...);}
}
using namespace VividCycle;
int n, ml, md, u, v, w, cnt[1001], dis[1001];
vector< pair<int, int> > g[1001];
queue<int> q;
int main() {
    read(n, ml, md);
    while(ml--) {
        read(u, v, w);
        g[u].push_back(make_pair(v, w));
    }
    while(md--) {
        read(u, v, w);
        g[v].push_back(make_pair(u, -w));
    }
    fu(i, 2, n) g[i].push_back(make_pair(i - 1, 0));
    fu(i, 1, n) g[0].push_back(make_pair(i, 0));
    memset(dis, 0x3f, sizeof(dis));
    dis[0] = 0;
    q.push(0);
    while(!q.empty()) {
        u = q.front();
        q.pop();
        ++cnt[u];
        if(cnt[u] > n) return 0 & puts("-1");
        for(const auto& i : g[u]) {
            if(dis[u] + i.second < dis[i.first]) {
                dis[i.first] = dis[u] + i.second;
                q.push(i.first);
            }
        }
    }
    memset(cnt, 0, sizeof(cnt));
    memset(dis, 0x3f, sizeof(dis));
    dis[1] = 0;
    q.push(1);
    while(!q.empty()) {
        u = q.front();
        q.pop();
        ++cnt[u];
        if(cnt[u] >= n) return 0 & puts("-1");
        for(const auto& i : g[u]) {
            if(dis[u] + i.second < dis[i.first]) {
                dis[i.first] = dis[u] + i.second;
                q.push(i.first);
            }
        }
    }
    if(dis[n] == 0x3f3f3f3f) return 0 & puts("-2");
    write(dis[n] - dis[1], ' ');
    flush();
    return 0;
}

先存一下。