求助,差分约束过不了样例
查看原帖
求助,差分约束过不了样例
235561
samzhangjy楼主2022/8/13 17:36

rt,样例输出:

0 -2 0

对着题解改了半天没找出来……大佬们帮忙看一下吧()

(必关注qwq)

代码:

// Problem: P5960 【模板】差分约束算法
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P5960
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include <memory.h>

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int N = 5 * 1e3 + 10;

int h[2 * N], vtx[2 * N], nxt[2 * N], w[2 * N], idx, vis[2 * N], dis[2 * N];
int cnt[2 * N], op, a, b, c;
int n, m;
queue<int> q;

void addEdge(int a, int b, int c) {
    vtx[idx] = b, nxt[idx] = h[a], w[idx] = c, h[a] = idx++;
}

bool spfa(int s) {
    memset(dis, 0x3f, sizeof(dis));
    memset(vis, 0, sizeof(vis));
    dis[s] = 0;
    q.push(s);
    vis[s] = 1;
    while (!q.empty()) {
        int tmp = q.front();
        q.pop();
        vis[tmp] = 0;
        int p = h[tmp];
        while (p != -1) {
            int v = vtx[p];
            if (dis[v] > dis[tmp] + w[p]) {
                dis[v] = dis[tmp] + w[p];
                if (!vis[v]) {
                    cnt[v]++;
                    if (cnt[v] == n + 1) return 0;
                    q.push(v);
                    vis[v] = 1;
                }
            }
            p = nxt[p];
        }
    }
    return 1;
}

int main() {
    memset(h, -1, sizeof(h));
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        addEdge(n + 1, i, 0);
    }
    for (int i = 1; i <= m; i++) {
        cin >> a >> b >> c;
        addEdge(b, a, c);
    }
    if (spfa(n + 1)) {
        for (int i = 1; i <= n; i++) cout << dis[i] << " ";
        cout << endl;
    } else {
        cout << "NO" << endl;
    }
    return 0;
}

thx!

2022/8/13 17:36
加载中...