差分约束 : 糖果

糖果

分析

\(要求糖果的最小值,应该把不等式处理成x_i \ge x_j+c的形式,求最长路.\)

约束关系
  • \(x_i \ge 1\)
  • \(x_i\ge x_0+1\)
  • \(x_0=0\)

\(当负环导致TLE,可以尝试将queue换成stack.\)

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1e5 + 7, M = 3e5 + 7;
int n, m;
int h[N], e[M], w[M], ne[M], idx;
ll dist[N];
int q[N], cnt[N];
bool st[N];

void add(int a, int b, int c) {
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

bool spfa() {
    memset(dist, -0x3f, sizeof dist);
    dist[0] = 0;
    int hh = 0, tt = 1;
    q[0] = 0;
    st[0] = true;
    while (hh != tt) {
        int t = q[--tt];
        st[t] = false;
        for (int i = h[t]; ~i; i = ne[i]) {
            int j = e[i];
            if (dist[j] < dist[t] + w[i]) {
                dist[j] = dist[t] + w[i];
                cnt[j] += 1;
                if (cnt[j] >= n + 1) return false;
                if (!st[j]) {
                    q[tt++] = j;
                    st[j] = true;
                }
            }
        }
    }
    return true;
}

int main() {
    IO;
    cin >> n >> m;
    memset(h, -1, sizeof h);
    while (m--) {
        int x, a, b;
        cin >> x >> a >> b;
        if (x == 1) add(b, a, 0), add(a, b, 0);
        else if (x == 2) add(a, b, 1); //b >= a + 1
        else if (x == 3) add(b, a, 0);
        else if (x == 4) add(b, a, 1);
        else add(a, b, 0);
    }
    for (int i = 1; i <= n; ++i) add(0, i, 1); //xi >= x0 + 1, x0 = 0
    if (!spfa()) puts("-1");
    else {
        ll res = 0;
        for (int i = 1; i <= n; ++i) res += dist[i];
        cout << res << '\n';
    }
}
posted @ 2021-02-17 17:09  phr2000  阅读(56)  评论(0编辑  收藏  举报