差分约束系统

原理

见《进阶指南》第393页。

模板题

洛谷-P5960-【模板】差分约束算法open in new window

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int N = 5010;
struct edge {
    int to, next, w;
};
edge e[2 * N];
int idx, head[N];
int n, m;
int dis[N], cnt[N];
bool mark[N];

void add_edge (int u, int v, int w) {
    e[idx].w = w;
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
bool spfa () {
    memset(dis, 0x3f, sizeof(dis));

    queue<int> q;
    dis[0] = 0;
    q.push(0);
    mark[0] = true;
    while (!q.empty()) {
        int cur = q.front();
        q.pop();
        mark[cur] = false;
        for (int i = head[cur]; i != -1; i = e[i].next) {
            int to = e[i].to, w = e[i].w;
            if (dis[cur] + w < dis[to]) {
                dis[to] = dis[cur] + w;
                cnt[to] = cnt[cur] + 1;
                if (cnt[to] >= n + 1) return true; // 0 ~ n
                if (mark[to] == false) {
                    q.push(to);
                    mark[to] = true;
                }
            }
        }
    }
    return false;
}

int main () {
    memset(head, -1, sizeof(head));
    cin >> n >> m;
    for (int i = 1, u, v, w; i <= m; ++ i) {
        cin >> u >> v >> w;
        add_edge(v, u, w);
    }

    for (int i = 1; i <= n; ++ i)
        add_edge(0, i, 0);
    if (spfa() == true) {
        cout << "NO" << endl;
    } else {
        for (int i = 1; i <= n; ++ i)
            cout << dis[i] << ' ';
    }
    return 0;
}
最后修改于: