关于差分约束的一点学习

· · 个人记录

来自P3275糖果

题目中给出了五种不等式限制

我们将其从数学转化为图上边权

dis[v]≥dis[u]+w 与xv≥xu+w完全一致

所以可以使用差分约束算法

因为是大于等于所以我这里选择使用最长路求解,SPFA求最长路的时间复杂度是O(VE),会被卡,又由于是有向图,所以选择了拓扑排序求O(V+E)

拓扑排序的使用前提是途中无环,显然本题建图后可以有环,所以我们先用tarjan缩点。

缩点后发现若强连通分量内若有正权值1,则必有正环存在,即不存在最长路。所以输出-1的充要条件就是店内是否有正权值边。这个我们可以直接通过遍历一遍找出

这就是这道题的整体思路下面是代码:

#include <bits/stdc++.h>
#define int long long
using namespace std;

struct edge {
    int to, val;
};
int low[100010], dfn[100010], scc[100010], in[100010], sz[100010];
int dis[100010], dag[100010];
bool vis[100010];
vector<edge> e[100010];
vector<edge> escc[100010];
stack<int>s;
int n, m, timer, cnt;

void tarjan(int x)
{
    low[x] = dfn[x] = ++timer;
    vis[x] = 1;
    s.push(x);
    for (auto t : e[x]) {
        int to = t.to;
        if (!dfn[to]) {
            tarjan(to);
            low[x] = min(low[x], low[to]);
        }
        else if (vis[to]) {
            low[x] = min(low[x], dfn[to]);
        }
    }
    if (low[x] == dfn[x])
    {
        int v = 0;
        cnt++;
        do {
            v = s.top();
            s.pop();
            vis[v] = 0;
            scc[v] = cnt;
            sz[cnt]++;
        } while (v != x);
    }
}

void topu()
{
    queue<int>q;
    for (int i = 1; i <= cnt; i++)
    {
        if (!in[i])q.push(i);
    }
    while (q.size()) {
        int t = q.front();
        q.pop();
        for (auto tmp : escc[t]) {
            int to = tmp.to;
            int val = tmp.val;
            in[to]--;
            if (!in[to])q.push(to);
            if (dag[to] < dag[t] + val) {
                dag[to] = dag[t] + val;
            }
        }
    }
}

signed main() {
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int op, a, b;
        cin >> op >> a >> b;
        if (op == 1) {
            e[a].push_back({ b, 0 });
            e[b].push_back({ a, 0 });
        }
        else if (op == 2) {
            e[a].push_back({ b, 1 });
        }
        else if (op == 3) {
            e[b].push_back({ a, 0 });
        }
        else if (op == 4) {
            e[b].push_back({ a, 1 });
        }
        else if (op == 5) {
            e[a].push_back({ b, 0 });
        }
    }
    for (int i = 1; i <= n; i++) {
        e[0].push_back({ i, 1 });
    }
    tarjan(0);
    for (int i = 0; i <= n; i++) {
        for (auto t : e[i]) {
            if (scc[i] == scc[t.to] && t.val) {
                cout << -1;
                return 0;
            }
            else if (scc[i] != scc[t.to]) {
                escc[scc[i]].push_back({ scc[t.to],t.val });
                in[scc[t.to]]++;
            }
        }
    }
    topu();
    int ans = 0;
    for (int i = 1; i <= cnt; i++)
    {
        ans += dag[i] * sz[i];
    }
    cout << ans;
}